2017-12-15 8 views
0

CのバックグラウンドからのC++の学習。ファイルへのC++ cinの入力

私がしたいことは、コンソール入力をファイルにコピーすることです。このプロハウスでは、私はこれを行う:

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

最後の行が出力ファイルにないことを正しく実行するのは問題です。 すなわち:私は

Hello 
My Name Is 
Lucas 
Goodbye! 

を入力すると、 "さようなら" は、事前にファイルにのみ

Hello 
My Name Is 
Lucas 

Thxsを表示されません。

+1

'cin.eof()'は使わないでください。 loop条件として 'cin.get()'を使います。 – iBug

+1

'getline(cin、line)'を使用する –

+3

「なぜwhile(!feof(file))」が常に間違っているのですか?](https://stackoverflow.com/questions/5431941/why-is-while- feof-file-always-wrong) –

答えて

1

これは通常、(でもCで)アンチパターンです:

while (!cin.eof()) 

これで問題のカップルがあります。エラーがある場合は、無限ループに入ります(文字を読むことはできますが、これを割り引くことができます)。

しかし、主な問題は、EOFが唯一の事実の後に検出されていることである。

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. 

あなたが前に、読み出し動作の後に、それをチェックする必要はありません。出力が出力に書き込まれる前に、読み取りが正常に動作していることを常にテストします。

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

これはおそらく入力または書き込み出力を読み取る最も効率的な方法ではないことに注意してください。

+0

私は質問に答えてコードを解決しましたが、それでも私には同じエラーが表示されます。 – Lucas

関連する問題