2017-10-01 12 views
-1

このプログラムでは、3つの整数をテキストファイルに書き込んだ後、ファイルに入力された偶数の整数を表示する必要があります。私のコードはエラーなしで実行され、数値はファイルに書き込まれますが、if文内のcout文は何らかの理由で表示されません。ファイルに書き込まれた偶数の数を書き込んで表示する(初級C++ Visual Studio)

#include <iostream> 
#include <fstream> 
using namespace std; 
int main() 
{ 
    int num1 = 0; 
    int num2 = 0; 
    int num3 = 0; 
    ofstream outFile; 
    cout << "Enter three integers:\n"; 
    cout << "#1: "; 
    cin >> num1; 
    cout << "#2: "; 
    cin >> num2; 
    cout << "#3: "; 
    cin >> num3; 
    outFile << num1 << endl << num2 << endl << num3 << endl; 
    outFile.close(); 
    if (num1 % 2 == 0) 
    { 
     cout << "One even number was written to the file."; 
    } 
    else if (num2 % 2 == 0) 
    { 
     cout << "Two even numbers were written to the file."; 
    } 
    else if (num3 % 2 == 0) 
    { 
     cout << "Three even numbers were written to the file."; 
    } 
    else 
    { 
     cout << "No even numbers were written to the file."; 
    } 
    outFile.open("Text.txt", ios::app); 
    if (!outFile) 
     { 
      cout << "File did not open."; 
      return 1; 
     } 
    outFile << num1 << endl << num2 << endl << num3 << endl; 
    outFile.close(); 
    return 0; 
    system("pause"); 


} 
+0

デバッガでコードをステップ実行し、その理由を調べるまでの時間。 – tadman

+0

私はデバッガがF5だと思いますが、どうすればそれが役に立ちますか? –

+1

@SpencerCumbieだからこそ、デバッガが必要なのです!行ごとにステップを進め、コントロールの流れを見て、変数の値を調べて、なぜ意思決定が行われるかどうかを確認します。 –

答えて

0

あなたは異なるロジック使用することができます

int count = 0; 
if (num1 % 2 == 0) 
{ 
    ++count; 
} 
if (num2 % 2 == 0) 
{ 
    ++count; 
} 
if (num3 % 2 == 0) 
{ 
    ++count; 
} 
std::cout << "There were " << count << " even numbers written to the file.\n"; 

を上記のコードは偶数番号の数をカウントし、その値を出力します。 else節が不要です。

+0

本当にありがとう、これは私の問題でした。 if文を書き直す必要があることはわかっていました。オリジナルのコードではすべての可能性が説明されていなかったからです。この投稿に投票して、教師が必要だと言ってくれて本当に私を助けてくれてありがとう、ありがとう。このサイトはあなたのようなより多くのユーザーを必要とします。 –

関連する問題