首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

初学者提问关于读取字符串

2012-02-10 
菜鸟提问关于读取字符串刚接触c不久想从文件中以 / 分割的字符串中读取每段数据,整个文件中字符串大致分

菜鸟提问关于读取字符串
刚接触c不久

想从文件中以 "/ "分割的字符串中读取每段数据,整个文件中字符串大致分三类,如:

FHKD/ECNY/SCNY/....

FHKD/SCNY/...

A/FHKD/   /SCNY/...

每一项都要赋给相对应的变量

如果只是这几项就if..else   if..搞了,但问题是后面还有很多项

请问有没有其他解决方法?

经验不多,望不吝赐教

[解决办法]
MFC: CString::Find
C++: string::find string::left string::right
C api: strchr
[解决办法]
用GetLine循环读取整行,然后循环用strtoken分解字符串,逐个对其进行操作,很简单的
[解决办法]
函数名: strtok
功 能: 查找由在第二个串中指定的分界符分隔开的单词
用 法: char *strtok(char *str1, char *str2);
程序例:

#include <string.h>
#include <stdio.h>

int main(void)
{
char input[16] = "abc,d ";
char *p;

/* strtok places a NULL terminator
in front of the token, if found */
p = strtok(input, ", ");
if (p) printf( "%s\n ", p);

/* A second call to strtok using a NULL
as the first parameter returns a pointer
to the character following the token */
p = strtok(NULL, ", ");
if (p) printf( "%s\n ", p);
return 0;
}


[解决办法]
#include "iostream "
#include "fstream "
#include "string "
#include "vector "

using namespace std;

int main()
{
ifstream ifile( "test.txt ");

if (ifile.fail())
return 1;

vector <string> buffer;
string str;

while (!ifile.eof())
{
ifile> > str;
size_t s = 0;
size_t p = 0;

while ((s = str.find( '/ ', s + 1)) != str.npos)
{
string sub = str.substr(p, s - p);
p = s + 1;
buffer.push_back(sub);
}
}

ifile.close();

for (size_t i = 0; i < buffer.size(); ++i)
cout < <buffer[i] < <endl;

return 0;
}

热点排行