使用sscanf分割字符串时出现的问题
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void main()
{
ifstream openf( "test.txt "); //从test.txt中读取文件
string line;
char o[20], f[20], s[10], t[10];
while(!openf.eof()) //判断是否到达文件尾
{
getline(openf,line);
char p[200];
strcpy(p, line.c_str());
cout < <line < <endl;
cout < <p < <endl;
sscanf(p, "%[^ ', '],%[^ ', '],%[^ ', '],%[^ ', '] ", o, s, t, f);
printf( "%d\n%d\n%d\n%d\n ",o, f,s, t);
}
}
test.txt中存放的是用 ", "分割开的数据,如:41,42,43,44
51,52,53,54
61,62,63,64
...
p[200}经处理和line所带数据相同
使用sscanf分割字符串p时得到的结果不是希望得到的数据,而且printf( "%d\n%d\n%d\n%d\n ",o, f,s, t)好象重复输出了,不知道哪个环节出问题了
[解决办法]
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void main()
{
ifstream openf( "test.txt "); //从test.txt中读取文件
string line;
char o[20]={0};
char f[20]={0};
cahr s[10]={0};
char t[10]={0};
while(!openf.eof()) //判断是否到达文件尾
{
getline(openf,line);
char p[200];
strcpy(p, line.c_str());
cout < <line < <endl;
cout < <p < <endl;
sscanf(p, "%[^,],%[^,],%[^,],%[^,] ", o, s, t, f);
printf( "%s\n%s\n%s\n%s\n ",o, f,s, t);
}
}