c语言,如何读取逗号分隔的字符串,将逗号间的字符串分别提取出来?

如题所述

先将所有的读进来存在一个字符串中,然后用字符分割函数strtok()//具体可参见API
例如:
char str[] = "now # is the time for all # good men to come to the # aid of their country";
char delims[] = "#";
char *result = NULL;

result = strtok( str, delims );

while( result != NULL ) {
printf( "result is \"%s\"\n", result );
result = strtok( NULL, delims );
}

以上代码的运行结果是:
result is "now "
result is " is the time for all "
result is " good men to come to the "
result is " aid of their country"
温馨提示:答案为网友推荐,仅供参考
第1个回答  2021-01-24
。。。省略头文件,int mian等。这里用到std::getline()

using namespace std;
getline(myfile, line, ','); //getline读myfile进string line,第三个变量很有用,定义是读取字符直到第三格变量被找到(这里是逗号‘,’)。如果不定义默认是换行符\n。
while (line.length() != 0) //如果读取不为空

{
cout << line << ' '; //打印第一段文字
getline(myfile, line); //接着识别,直到换行。如果还要找逗号就用上面的三变量方法。
cout << line << '\n'; //打印第二段
getline(myfile, line, ',');
}

我这个文件是读取两列的数据用的,格式是.csv。若有两列数据,那么.csv就是一行两个数据,中间用逗号隔开。本回答被网友采纳