使用 std::cin 函数后如何修复从文件读取

How to fix reading from file after using std::cin function

我的 C++ 代码有问题。

当我运行这段代码时:

#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;
}

输出应该是:

enter your text : alikamel // for example
then write it to file
data file contains : // file contents

但我得到的是这个:

enter your text : ass // for example
and it write it to file
then display
data file contains : // nothing ??

为什么不显示文件内容,有什么问题吗?

我假设文件是​​空的,在这种情况下,你可以这样做

    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();

正如评论中提到的那样...您也可以使用 ifstreamofstream 来更好地理解

您的问题是您正试图从文件末尾开始读取。

fstream 保存指向文件中当前位置的指针。 写完文件后,这个指针指向末尾,准备下一个写命令。

因此,当您尝试在不移动指针的情况下从文件中读取时,您是在尝试从文件末尾开始读取。

您需要使用seekg移动到文件开头才能阅读您写的内容:

file << s;
cout << "\ndata file contains :";

file.seekg(0);

while(getline(file, line))
{
    cout << "\n" << line;
}