简体   繁体   English

如何使用if else语句

[英]How to use if else statement

Today I want to test if a user types the word "yes" in console application, then the function will proceed, however, I am unable to do so. 今天,我想测试用户是否在控制台应用程序中键入单词“ yes”,那么该功能将继续进行,但是,我无法这样做。 (I am a new person, sorry) (我是一个新朋友,对不起)

Any help on this? 有什么帮助吗? I know when testing a variable like.. int x = 14, and if (a < 14) print something.. but instead of number I'd like to try with text. 我知道在测试像.. int x = 14的变量时,并且如果(a <14)打印某些内容..但是我想尝试使用文本而不是数字。

Here is the source code: 这是源代码:

int main()
 {
   char a = yes;
   char b = no;
   cout << "hi, press yes to start or no to cancel";
   cin >> a;

  if (a == yes)
   { 
  cout << "Cool person";
   }
  else if(b == no)
   {
  cout << "not a cool person";
  }
}

I keep getting "yes" is not defined in scope. 我不断得到“是”的定义范围。 Any help would be appreciated. 任何帮助,将不胜感激。 Thank You! 谢谢!

At a bare minimum, the following problems exist in your code: 至少,您的代码中存在以下问题:

  • Tokens yes and no are identifiers. 令牌yesno是标识符。 If you wanted them to be characters, that would be 'yes' and 'no . 如果您希望他们成为角色,那就应该是'yes''no Except that they're not characters since they're too long. 除非它们不是字符,否则因为它们太长。 So, they should probably be strings like "yes" and "no" . 因此,它们可能应该是"yes""no"类的字符串。

  • The b variable is totally useless here, you should have one variable for receiving information from the user and checking it against multiple possible values. b变量在这里完全没有用,您应该有一个变量用于接收来自用户的信息并针对多个可能的值进行检查。 It's also a good idea to choose meaningful variable names. 选择有意义的变量名也是一个好主意。

  • You aren't including the requisite headers, nor are you using the correct namespace for the std functions and types (either by explicitly prepending std:: to each, or with a using namespace std for them all). 您没有包括必需的标头,也没有为std函数和类型使用正确的命名空间(通过在每个函数和类型之前显式地添加std:: ,或者为它们全部using namespace std )。

With that in mind, try out the following program as a starting point for your further education: 考虑到这一点,请尝试以下程序作为您继续学习的起点:

#include <iostream>
#include <string>

int main() {
    std::string userInput;

    std::cout << "Hi, enter yes to start or no to cancel: ";
    std::cin >> userInput; // probably better: std::getline(std::cin, userInput);

    if (userInput == "yes") {
        std::cout << "Cool person\n";
    } else if (userInput == "no") {
        std::cout << "Not a cool person\n";
    } else {
        std::cout << "Hey, can't you read? I said yes or no :-)\n";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM