[英]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.