【问题标题】:How do I show my switch function that my string variable equals user input如何显示我的 switch 函数,我的字符串变量等于用户输入
【发布时间】:2017-01-04 01:48:40
【问题描述】:

我有一个程序,其字符串变量等于用户输入的任何内容。我正在尝试使用 switch 语句根据用户键入的字母显示特定消息,但不知道如何显示 switch程序它是一个输入。感谢您的帮助,部分代码如下。

cin >> ans1;
switch(ans1 == "") {
    {case "A" : cout << ": Sorry, the right answer was C.";
    break;}
    {case "B" : cout << ": Sorry, the right answer was C.";
    break;}
    {case "C" : cout << ": Correct! Wow, your pretty smart!";
    break;}
    {case "D" : cout << ": Sorry, the correct answer was C.";
    break;}

【问题讨论】:

  • switch(ans1 == "") ??那只能有值真或假,而不是“A”,“B”等......
  • 在这里查看您问题的所有答案:stackoverflow.com/questions/388242/…
  • 另外,您不能将stringswitch 语句一起使用。但您可以使用char。为什么不直接使用if/elseif (ans1 == "C") {cout &lt;&lt; "Correct;} else {cout &lt;&lt; "Wrong";}
  • 我怎么说ans1等于用户输入,如果输入是a、b、c、d
  • 哦,好的,谢谢你,这更有意义@JohnnyMopp

标签: c++ switch-statement cin


【解决方案1】:

您可以使用 if/else statement(即 ans1 == 'C'),而不是使用带有等于用户输入的变量的 switch statement

if (ans1 == 'C') {
    cout << "Correct";
} else {
    cout << "Wrong";
}

谢谢JohnnyMopp5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多