簡體   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