简体   繁体   中英

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

I have some problem with my C++ code.

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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