【问题标题】:How to apply arithmetic operation on strings in C++? [closed]如何在 C++ 中对字符串应用算术运算? [关闭]
【发布时间】:2017-10-11 15:48:49
【问题描述】:

我想创建一个程序,它读取一个包含两个数字和一个运算符的字符串并打印出结果。它在算术运算符上不断显示错误。例如,如何将两个字符串相加?

int main()
{
    string number1;
    string number2;
    string operation;
    string answer;

    cout << "Enter numbers with respective operations";
    cout << "number 1";
    cin >> number1; 
    cout << "number2";
    cin >> number2;
    cout << "operation";
    cin >> operation;
    if (operation == "+")
    {
        answer = number1 + number2;
        cout << "the sum is   " << answer << endl;
    }
    else if (operation == "-")
    {
        answer = number1 - number2;
        cout << "the difference is   " << answer << endl;
    }
    else if (operation == "*")
    {
        answer = number1 * number2;
        cout << "the product is   " << answer << endl;
    }
    else if (operation == "/")
    {
        answer = number1 / number2;
        cout << "the answer is   " << answer << endl;
    }
    else
    {
        cout << "invalid input" << endl;
    }
    getchar();
    return 0;
} 

【问题讨论】:

  • 您期望string 除以string 的结果是什么??
  • 有什么错误?
  • 根据您的代码,数字没有理由成为字符串,为什么是?因为它们是字符串,如果你想用它们进行计算,你需要将它们转换为数字。
  • 你必须先convert the string to a numeric type 然后对该值进行计算。
  • @xyious -- 您不能将字符串转换为数字;你可以转换它。强制转换是您在源代码中编写的内容,用于告诉编译器进行转换。

标签: c++


【解决方案1】:

您需要将输入类型更改为数字类型,因此您读取的是实际数字,而不是它们的字符串表示形式。正如您所看到的herestring 重载的运算符中唯一一个是+ - 这是用于字符串连接的。

正在改变...

string number1;
string number2;
string answer;

...到...

double number1;
double number2;
double answer;

...应该可以解决您的问题。

或者,您可以像现在一样读取字符串,然后将它们转换为数字(请参阅here),但这只是在您不需要时增加了更多工作。 除非您想检测无效的数值(如1234abc8),在这种情况下读取字符串然后解析并检查无效输入是个好主意。

【讨论】:

  • 是的,我总是迟到 1 秒,但最终我放弃了更新我的 cmets ;)
  • 我可以通过将字符串更改为双精度数据类型来做到这一点。但这是一个赋值题,通过字符串取两个操作数和一个运算符,进行基本的计算操作。
  • @Sumair 然后看看this,进行转换。
【解决方案2】:

您的示例中的number1number2 都是字符串,它们不支持将值相加。您可以简单地将 number1number2 以及 answer 的类型切换为整数:

int main()
{
    float number1;
    float number2;
    string operation; // could switch this to char too
    float answer;
    // ...

如果你真的想使用字符串,你可以使用 &lt;sstream&gt; 中包含的字符串流: http://www.cplusplus.com/reference/sstream/stringstream/stringstream/

Edit1:如果您关心后浮点值,float 可能是更好的类型。

【讨论】:

  • ints 可能不会产生 OP 想要的除法结果
  • 基本上这是我面临困难的作业问题。问题是。创建一个程序,该程序读取一个包含两个数字和一个运算符的字符串并打印出结果。该字符串将由您的程序解释。
  • 在这种情况下,您将需要使用字符串流。
猜你喜欢
  • 2018-07-06
  • 2013-02-19
  • 1970-01-01
  • 2020-03-17
  • 2012-09-12
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多