简体   繁体   中英

C++ cin input to file

im learning C++ from a C background.

What i want to do is copy the console input to a file. For this proupouse i do this:

 #include "stdafx.h"
 #include <fstream>
 #include <iostream>
 using namespace std;
 int main()
 {
     ofstream file_out;
     file_out.open("test.txt");
     char char_input;
     while (!cin.eof())
     {
         cin.get(char_input);
         file_out << char_input;
     } 
     file_out.close();
     return 0;
}

The thing is that works right execpt that the last line isn't in the output file. IE: if i enter

Hello
My Name Is
Lucas
Goodbye!

The "Goodbye" doesn't appear in the file only

Hello
My Name Is
Lucas

Thxs in advance.

This is usually an anti-pattern (even in C):

while (!cin.eof())

There are a couple of issues with this. If there is an error you go into an infinite loop (reading characters though we can discount this).

But the main problem is that EOF is only detected after the fact:

cin.get(char_input);
// What happens if the EOF just happend.
file_out << char_input;
// You just wrote a random character to the output file.

You need to check for it after a read operation, not before. Always test that the read worked before writing it to the output.

// Test the read worked as part of the loop.
// Note: The return type of get() is the stream.
//       When used in a boolean context the stream is converted
//       to bool by using good() which will be true as long as
//       the last read worked.
while (cin.get(char_input)) {
    file_out << char_input;
}

I would note this is probably not the most efficient way to read input or write output.

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