简体   繁体   中英

Why is getline (from a file) to cout (that line) not printing the line?

This is my code here.

ifstream inFile;
ofstream outFile;

string line, line2;

inFile.open("DATA.txt");
outFile.open("DATA.txt");

getline(inFile, line);
cout << line;
getline(inFile, line2);
cout << line2;

getline(cin, line);
getline(cin, line2);

outFile << line << "\n" << line2;

From what I understand, getline(inFile, line) should assign the first line of my text file to a string named line. Then the cout << line should print that string into the cmd window. This is not working though.

I am able to input just fine using getline(cin, line) and outFile though. The file gets updated and I can see what I typed in it, but it just doesn't properly read and print the lines.

ps This is my first question and I'm not entirely sure how to ask it in the title so I'm open to criticism.

On most platforms, std::cout typically buffers output data and does not flush to the console until a line break is output, or the buffer is flushed explicitly.

Try using:

cout << line << '\n';

Or:

cout << line << endl;

If you don't want to output line breaks, use:

cout << line << flush;

So I figured it out. When I had

inFile.open("DATA.txt");
outFile.open("DATA.txt");

I think the outFile.open overwrote the inFile.open, causing only the output part to work. Simply moving the outFile.open to before the output part instead of before everything fixed this problem. I'm sure there are several other sloppy things about my code, but that fixed it to the point of actually working.

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