繁体   English   中英

无法从文本文件中读取并存储到字符串中

[英]Unable to read from text file and store into string

我有一个文本文件

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

相反,我得到了

我的代码出了什么问题?

while循环结束时有一个分号:

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

这将导致要执行的提取,但只有当循环结束确实foo得到打印。 最后一次提取不会提取任何foo为空的原因,因此是空输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM