2017-02-01 1 views
-4

Frage: jedes Mal, wenn ich das Programm ausführen und ich eingeben, wer Sie sind, sagt es Fehlerwert von a stimmt nicht überein, was vor sich geht? (Ja, ich bin ein noob zu C++) Code:Ich laufe weiter in Probleme mit, wenn elif und sonst in 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' liest nur ein Wort. Wie kann es gleich "Wer bist du" sein? – Barmar

+1

Lesen Sie die Zeichenfolge mit std :: getline() –

+2

Wenn Sie versucht haben, "a" zu drucken, hätten Sie das Problem sofort gesehen. – Barmar

Antwort

1

Der Operator >> für Streams und Strings Eingänge Worte von weißen Leerzeichen getrennt. Sie sollten eine Funktion verwenden, die mehrere Wörter gleichzeitig lesen kann, bis die Eingabetaste gedrückt wird. Zum Beispiel können Sie die Standardfunktion verwenden std::getline

Auch müssen Sie Header <string> enthalten. Hier

Sie sind

#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

Sie verwenden getline Funktion sein muss, wenn Sie Eingabesatz wollen.

das war sehr komplex.

in Kürze, cin >> kann nicht compre NULL und Raum;

, wenn Sie schreiben, "die ru" in CLI dann Pufferspeicher unter

'w', 'h', 'o', '', 'r', '', 'u', NULL

aber cin ist nur speichern "wer" 3 Wort becaue Raum.

müssen Sie getline wie diese

getline(cin,a); 

viel Glück verwenden!