[英][C++]Importing text file - Problems with getline()
我在使用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
不要这样做:
while(!fx.eof())
{
getline(fx,linha); // Here you have to check if getline() actually succeded
// before you do any further processing.
// You could add if (!fx) { break;}
// STUFF;
}
但更好的设计是:
while(getline(fx,linha)) // If the read works then enter the loop otherwise don't
{
// STUFF
}
你没有超越逗号:
inic=pos; // pos is the position of the last ',' or std::string::npos
pos=linha.find(',',inic); // So here pos will be the same as last time.
// As you start searching from a position that has a comma.
ifstream
有一个getline
函数,它接受char*
作为第一个参数,最大长度作为第二个参数。
ifstream
还有你应该用于输入的operator>>
,但它会读到空白,这不是你想要的。
你正在使用的::getline
也应该有效,但是假设流是正常的,如前所述,你没有正确检查。 您应该在调用之后检查错误,因为如果您达到EOF或出现错误,您将无法知道,直到整个循环完成。
另外,文件中有什么? 也许你得到的是正确的结果?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.