简体   繁体   中英

error: no match for 'operator-' When trying to subtract strings

I am trying to subtract these two numbers, and I keep getting this error.

code:

#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;

}

The error is on the line of code that says

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

The program will not ever compile with the subtraction sign (-) there, and if I change it to a addition sign (+) then it will compile, but the numbers will not properly add, and the end number just ends up being a place holder number for the variable (for example, 2555354 or something like that). Am I missing something here? Any help would be appreciated.

You are trying to add and subtract strings, not numbers. While addition works (and results in string concatenation), subtracting strhings doesn't make sense. Use numbers:

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

Depending on your applications need, you might want to use a different numeric type, eg double .

Although others have pointed out rightly..

To get this code working, the string values need to be treated as an integer:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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