2017-02-01 1 views
-4

質問: (はい、私はC++にnoobのだ) コード:もし私がプログラムを実行するたびにエラーの値が何が起こっているかとは違うと言う人を入力するたびに、私はelifとか他のC++で問題に陥っています

#include <iostream> 
using namespace std; 

int main() { 

    // local variable declaration: 
    string a; 
    cin >> a; 
    // check the boolean condition 
    if(a == "hello") { 
     // if condition is true then print the following 
     cout << "hi" << endl; 
    } else if(a == "who are you") { 
     // if else if condition is true 
     cout << "a better question is who are you?" << endl; 
    } else if(a == "what am i doing") { 
     // if else if condition is true 
     cout << "reading this output " << endl; 
    }else { 
     // if none of the conditions is true 
     cout << "Error Value of a is not matching" << endl; 
    } 
    return 0; 
} 
+3

'cin >> a'は1語だけを読みます。あなたは誰ですか? – Barmar

+1

std :: getline()を使用して文字列を読み込みます –

+2

'a'を印刷しようとするとすぐに問題が発生していました。 – Barmar

答えて

1

オペレータ>>ストリームと文字列のためには、空白で区切られた単語を入力します。あなたはEnterキーが押されるまでいくつかの言葉を一度に読むことができる機能を使うべきです。たとえば、標準機能を使用することができますstd::getline

また、<string>ヘッダーを含める必要があります。ここで

あなたはあなたが入力文をしたい場合のgetline関数を使用するにする必要があり

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string s; 

    if (std::getline(std::cin, s)) 
    { 
     // check the boolean condition 
     if (s == "hello") 
     { 
      // if condition is true then print the following 
      std::cout << "hi" << std::endl; 
     } 
     else if (s == "who are you") 
     { 
      // if else if condition is true 
      std::cout << "a better question is who are you?" << std::endl; 
     } 
     else if (s == "what am i doing") 
     { 
      // if else if condition is true 
      std::cout << "reading this output " << std::endl; 
     } 
     else 
     { 
      // if none of the conditions is true 
      std::cout << "Error Value of a is not matching" << std::endl; 
     } 
    } 

    return 0; 
} 
-1

です。

非常に複雑でした。

まもなく、cin >> cantはNULLとスペースを含んでいません。

あなたが書いた場合、CLIで "ruが誰が"、その後、 'H'、 'O'、 ''、 'R'、 ''、 'U' 'w' は

の下に店をバッファNULL

しかし、cinは "who"という3ワードのスペースしか保存していません。

あなたはこの

getline(cin,a); 

幸運のようなのgetlineを使用する必要があります!

関連する問題