【发布时间】:2011-10-23 21:12:53
【问题描述】:
我在用 c++ 读取文本文件时遇到了麻烦,尤其是在将一行分配给变量时。
我有以下代码:
ifstream fx;
fx.open(nomeFich);
if(!fx)
{cout << "FX. nao existe!" <<endl;}
string linha="";;
int pos, inic;
while(!fx.eof())
{
getline(fx,linha);
if(linha.size() > 0)
{
cout << linha << endl;
inic=0;
pos=0;
pos=linha.find(",",inic);
cout << pos << endl;
string nomeL1(linha.substr(inic,pos));
cout << "atribuiu 1" << endl;
inic=pos;
cout <<"inic: " << inic << " pos:" << pos <<endl;
pos=linha.find(',',inic);
string nomeL2(linha.substr(inic,pos));
cout << "atribuiu 2" << endl;
inic=pos;
cout <<"inic: " << inic << " pos:" << pos <<endl;
pos=linha.find(',',inic);
cout << "atribuiu 3" << endl;
string dist(linha.substr(inic,pos));
当它执行cout << linha << endl; 时,它会返回类似:
===============================
我用谷歌搜索了很多,但找不到答案。 我是 C++ 新手,所以不要过多抨击 xD
【问题讨论】:
-
为什么不使用
fx.getline()? -
喜欢 linha=fx.getline();?它给出了一个错误..
-
fx >> linha;在我们的过程中。 -
您将处理太多行,因为在您读取文件末尾之前不会设置 eof。使用
while( getline( fx, linha ) ) { }