[英]How to fix reading from file after using std::cin function
I have some problem with my C++ code. 我的C ++代码有问题。
When I run this code: 当我运行此代码时:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string s;
string line;
fstream file("file.txt", ios::out | ios::in | ios::app);
cout << "enter your text :";
cin >> s;
file << s;
cout << "\ndata file contains :";
while(getline(file, line))
{
cout << "\n" << line;
}
cout << "\n";
system("pause");
return 0;
}
The output should be: 输出应为:
enter your text : alikamel // for example then write it to file data file contains : // file contents
But I get this instead: 但是我得到了这个:
enter your text : ass // for example and it write it to file then display data file contains : // nothing ??
Why doesn't it display the file contents, what is wrong? 为什么不显示文件内容,怎么了?
Your problems is that you are trying to read from the end of the file. 您的问题是您试图从文件末尾读取。
fstream
holds a pointer to the current position in the file. fstream
持有一个指向文件中当前位置的指针。 After you finish writing to file, this pointer points to the end, ready for the next write command. 完成写入文件后,此指针指向末尾,准备下一个写入命令。
So, when you are trying to read from the file without moving the pointer, you are trying to read from the end of the file. 因此,当您尝试在不移动指针的情况下读取文件时,您将尝试从文件末尾读取。
You need to use seekg
to move to the beginning of the file to read what you wrote: 您需要使用
seekg
移至文件的开头以读取所写内容:
file << s;
cout << "\ndata file contains :";
file.seekg(0);
while(getline(file, line))
{
cout << "\n" << line;
}
I am assuming the file is empty, in that case, you can do something like this 我假设文件为空,在这种情况下,您可以执行以下操作
fstream file("TestFile.txt", ios::out);
cout << "enter your text :";
cin >> s; // Take the string from user
file << s; // Write that string in the file
file.close(); // Close the file
file.open("TestFile.txt",ios::in);
cout << "data file contains :" << endl;
while(getline(file, line)) { //Take the string from file to a variable
cout << line << endl; // display that variable
}
file.close();
cin.get();
And as one of the comment mentions... you can use the ifstream
and ofstream
as well for better undersanding 正如评论中提到的那样...您也可以使用
ifstream
和ofstream
以获得更好的理解
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.