c++ 读取文件每行的前几列数据

读取文件每行的感叹号前面数据,感叹号后面是注释,不需要读取
比如TXT文件是
1 2 3 !点1坐标
2 3 4 !点2坐标
1 2 3 5 !四边形点号
。。。。。。

第1个回答  推荐于2016-11-05
① 你可以这样:
...

#include <limits>
..
ifstream ifs;
string str;
...

while (!ifs.eof())
{
getline(ifs, str, '!');
ifs.ignore(numeric_limits<streamsize>::max(), '\n' );
cout << str.c_str() << endl;

}
② 上面的还是不够好, 因为虽然ingore了, 但其实还是在stream里面, 不如你干脆getline到string里面, 然后自己在根据!符号分割string。

ifstream ifs;
string str;
string substr;

while (!ifs.eof())
{
getline(ifs, str);
substr = str.substr(0,str.find("!"));
cout << substr << endl;
}

上面只是示范代码,没有错误保护。。。本回答被提问者采纳
相似回答