【问题标题】:Unable to read from text file and store into string无法从文本文件中读取并存储到字符串中
【发布时间】:2014-02-04 09:27:45
【问题描述】:

我有一个文本文件

0 Po Tom Mr 123AlphabetStreet Netherlands Wulu 123456 D01 Malaysia SmallAdventure 231112 
0 Liu Jack Mr 123AlphabetStreet Italy Spain 123456 D02 Afghanistan TriersAdventure 030214

我正在尝试读取txt文件:Form.txt,将使用getline的每一行存储到变量foo

这是工作程序

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
   fstream afile;
   afile.open("Form.txt",ios::in);

   string foo;


    while (getline(afile,foo,'\n') );
    {
        cout<<foo
            <<endl;

    }

}

没有任何东西打印到控制台输出,我期待

0 Po Tom Mr 123AlphabetStreet Netherlands Wulu 123456 D01 Malaysia SmallAdventure 231112 
0 Liu Jack Mr 123AlphabetStreet Italy Spain 123456 D02 Afghanistan TriersAdventure 030214

相反,我得到了

我的代码有什么问题??

【问题讨论】:

  • 感谢您的回复。您的可执行文件目录中有Form.txt 文件吗?
  • @0x499602D2 是的,我有
  • while 循环之前添加一个 if (!afile) cout &lt;&lt; "Something's wrong"; 并让我知道它是否打印。
  • @0x499602D2 它不打印
  • 什么系统和编译器?

标签: c++ debugging text-files iostream


【解决方案1】:

while 循环的末尾有一个分号:

while (getline(afile, foo, '\n'));
//                               ^

这会导致执行提取,但只有在循环结束时才会打印foo。最后一次提取没有提取任何内容,这就是为什么 foo 为空,因此输出为空。

【讨论】:

    猜你喜欢
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多