错误:'operator-'不匹配当尝试减去字符串

时间:2018-03-25 05:07:59

标签: c++

我试图减去这两个数字,我一直收到这个错误。

代码:

#include <iostream>

using namespace std;


void Cal()
{
string Money = "back";
string TotPay = "back";
string Assets = "back";
cout << "At anytime, you can type the word 'back' to go back a step." << endl;
do{
    cout << "Enter your total amount of money: ";
    cin >> Money;
}while(Money == "back");
do{
    cout << "\nEnter the total of your payments: ";
    cin >> TotPay;
}while(TotPay == "back");
do{
    cout << "\nEnter the total value of your assets: ";
    cin >> Assets;
}while(Assets == "back");
cout << "Your net worth is " << (Money + Assets) - TotPay << "!";

}

int main()
{
string name;
string yn;
cout << "Enter your name please: ";
cin >> name;
cout << "\nHello " << name << ", today we are going to calculate your net worth.\n";
do{
    Cal();
    cout << "Would you like to calculate again? (yes/no)\n";
    cin >> yn;
}while(yn == "yes");
cout << "See ya!";
return 0;

}

错误出现在

代码行上
cout << "Your net worth is " << (Money + Assets) - TotPay << "!";

程序将不会在那里使用减法符号( - )进行编译,如果我将其更改为加号(+)则会编译,但数字将无法正确添加,并且结束编号最终会结束作为变量的占位符编号(例如,2555354或类似的东西)。 我在这里错过了什么吗? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您正在尝试添加和减去字符串,而不是数字。 虽然加法有效(并且会产生字符串连接),但减去强度并没有意义。使用数字:

int Money = 0;
int TotPay = 0;
int Assets = 0;

根据您的应用程序需要,您可能希望使用其他数字类型,例如double

答案 1 :(得分:0)

虽然其他人已正确指出......

要使此代码正常工作,需要将字符串值视为整数:

cout << "Your net worth is " << (stoi(Money) + stoi(Assets)) - stoi(TotPay) << "!";