【问题标题】:chained if-else not working (C++)链式 if-else 不起作用(C++)
【发布时间】:2015-09-04 14:33:21
【问题描述】:

我是一个初学者,我在使用链式 if-else 语句时遇到了问题。当我运行程序并输入我选择的项目时,它总是输出“无效条目。”。为什么它在 if 语句中等于它时不执行正确的功能?

谢谢,

不要

#include <iostream>
using namespace std;

int sum(int int1, int int2 ){

    return int1 + int2;

}

int difference( int int1, int int2 ){

    return int1 - int2;

}

int product( int int1, int int2 ){

    return int1 * int2;

}

int quotient( int int1, int int2 ){

    return int1 / int2;

}

int main(){

cout << "\nWelcome to the calculator.\n\n";
cout << "Please enter two numbers.\n\n";

int a;
int b;
cin >> a >> b;

cout << "What would you like to do with these numbers?\nHere are your options: add, subtract, multiply, or divide.\n\n";

string add;
string subtract;
string multiply;
string divide;

string choice;
cin >> choice;


if( choice == add )
    cout << sum( a, b );
else if ( choice == subtract )
    cout << difference( a, b );
else if ( choice == multiply )
    cout << product( a, b );
else if ( choice == divide )
    cout << quotient( a, b );
else 
    cout << "Invalid entry.\n"; 

return 0;

}

【问题讨论】:

  • 你可能应该添加一个语言标签
  • 感谢您的提示,这是我的第一篇文章。

标签: c++ if-statement chained


【解决方案1】:

有了这个声明:

string add;

您正在创建一个名为 add 的字符串变量,但尚未为其分配值。因此,当您将变量与用户输入进行比较时,程序会将 add 视为值 null,这与用户输入的值不相等。

你想给它赋值:

string add = "add";

所有其他字符串都一样。

并比较 std::string:

if(choice == add)

另一种方法,就是直接用常量字符串检查:

if(choice == "add"){
  //do something
}else if(choice == "subtract") 
  //do something else

【讨论】:

  • calculator.cpp:48:11: error: no member named 'equals' in 'std::__1::basic_string' 我在 mac 上使用 textedit。有问题吗?
  • strcmp 函数不适用于std::stringstd::string 类使用 operator==()。投反对票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 2023-03-13
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多