[英]Unable to read from text file and store into string
I have a text file 我有一个文本文件
0 Po Tom Mr 123AlphabetStreet Netherlands Wulu 123456 D01 Malaysia SmallAdventure 231112
0 Liu Jack Mr 123AlphabetStreet Italy Spain 123456 D02 Afghanistan TriersAdventure 030214
I am trying to read the txt file: Form.txt
, store each line using getline
into the variable foo
我正在尝试读取txt文件:
Form.txt
,使用getline
将每一行存储到变量foo
This is the working program 这是工作计划
#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;
}
}
Nothing gets printed to the console output , I am expecting 我期待没有任何东西打印到控制台输出
0 Po Tom Mr 123AlphabetStreet Netherlands Wulu 123456 D01 Malaysia SmallAdventure 231112
0 Liu Jack Mr 123AlphabetStreet Italy Spain 123456 D02 Afghanistan TriersAdventure 030214
Instead i get 相反,我得到了
What is wrong with my code ?? 我的代码出了什么问题?
You have a semicolon at the end of your while
loop: 在
while
循环结束时有一个分号:
while (getline(afile, foo, '\n'));
// ^
This causes the extraction to be performed but only the when the loop ends does foo
get printed. 这将导致要执行的提取,但只有当循环结束确实
foo
得到打印。 The last extraction doesn't extract anything which is why foo
is empty, hence the empty output. 最后一次提取不会提取任何
foo
为空的原因,因此是空输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.