繁体   English   中英

使用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持有一个指向文件中当前位置的指针。 完成写入文件后,此指针指向末尾,准备下一个写入命令。

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

您需要使用seekg移至文件的开头以读取所写内容:

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

file.seekg(0);

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

我假设文件为空,在这种情况下,您可以执行以下操作

    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以获得更好的理解

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM