[C++]导入文本文件 - 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 <<林哈<< endl;
它返回类似以下内容:
==========================================
我用谷歌搜索了很多,找不到答案。 我是 C++ 新手,所以不要过多抨击 xD
I've been having trouble with reading text files in c++, particularly when assigning a line to a variable.
I have the following code:
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));
When it does the cout << linha << endl;
it returns something like :
= = == = = = = == = = = = = = = == = = = = == = = = = =
I've googled it quite a lot and can't find an answer.
I'm new to C++ so don't bash too much xD
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要这样做:
但更好的设计是:
你无法越过逗号:
Don't do this:
But the better design is:
You are failing to move past the comma:
ifstream
有一个getline
函数,它接受char*
作为第一个参数,最大长度作为第二个参数。ifstream
还具有operator>>
您应该将其用于输入,但它会读取直到出现空格,这不是您想要的。您使用的
::getline
也应该可以工作,但这是假设流正常,正如前面提到的,您没有正确检查。您应该在调用它后检查错误,因为如果到达 EOF 或存在错误,您将在整个循环完成之前不会知道。另外,文件里有什么?也许你得到的是正确的结果?
ifstream
has agetline
function, it accepts achar*
as the first parameter and the maximum length as the second.ifstream
also hasoperator>>
which you should be using for input, but it will read till whitespace, which is not what you want.::getline
that you're using should also work, but that's assuming that the stream is OK, which as mentioned before, you don't check correctly. You should be checking for errors after calling it, because if you reach EOF or there's an error, you won't know until the whole loop is done.Also, what's in the file? Maybe what you're getting is the correct result?