我一直遇到 if elif 和 C++ 中的其他问题

i keep running into problems with if elif and else in c++

本文关键字:其他 问题 C++ 一直 遇到 if elif      更新时间:2023-10-16

问题:每次我运行程序并输入您是谁时,它都说 a 的错误值与正在发生的事情不匹配?(是的,我是 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;
}

运算符>>流和字符串输入用空格分隔的单词。您应该使用一个可以一次读取几个单词的功能,直到按下 Enter 键。例如,您可以使用标准函数std::getline

您还需要包含标题<string>

给你

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