使用getline()导入文本的问题
[C++]Importing text 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或有错误,您将无法知道,直到整个循环完成。
还有,文件里有什么?也许你得到的是正确的结果?
相关文章:
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- 绘制文本问题
- 用户定义的文本运算符(在原始模式下)存在问题
- 在 cout 中将线条表单文件与自定义文本组合时出现问题
- 在文本中查找半个单词"ABBA"的问题
- 从文件中读取文本时出现编码问题
- QTreeWidgetItem 突出显示文本问题
- 在 Qt C++ 中在自定义项委托上绘制文本时的性能问题
- opengl 飞行模拟器应用程序中的文本呈现问题
- 使用 c++ ifstream 读取文本文件问题
- 在C++中使用 Visual Studio 读取文本文件时遇到问题
- 我在编写从文本文件中读取数据并按升序打印的代码时遇到问题
- 使用 substr 提取文本文件时出现问题
- 问题 - 递归函数以返回文本文件排列
- 我在让我的代码输出整个链表时遇到问题.它只是输出我修改过的一些文本文件,而不是整个东西
- 解析基于逗号的文本文件时出现问题 (C++)
- UTF-16LE 编码问题与 Qt 文本编辑器用 C++ 编写
- 不确定我在阅读文本文件时的问题是什么
- 如何解决此问题,我需要从文本文件中导出一行
- SDL2 呈现文本问题