问题
I want to subtract two strings in this code, but it won't let me do it and gives an operator - error. This code basically tries to separate a full input name into two outputs: first and last names. Please Help! Thank you!
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
string employeeName, firstName, lastName;
int pos1, difference;
int main() {
cout << "Enter your full name: " << endl;
getline(cin, employeeName);
pos1 = employeeName.find(" ");
difference = pos1 - 0;
lastName = employeeName.erase(0,difference);
firstName = employeeName - lastName;
cout << lastName << firstName << endl;
system("pause");
return 0;
}
回答1:
You should use std::string::substr
. Subtracting strings like that is invalid.
firstName = employeeName.substr(0, employeeName.find(" "));
The first parameter is the starting index of the substring you want to extract and the second parameter is the length of the substring.
回答2:
How would you define a minus operator for a string? Would you subtract from the beginning? Or the end?
Moreover, what is "cat" - "dog"
? This operator wouldn't make sense.
Instead, you might want to use string indices, i.e. employeeName[i]
, and copy characters individually, or use std::string::substr
or std::string::erase
, as others have suggested.
I would find substr()
the easiest, due to its ability to remove sections of string (in this case, the first and last name).
回答3:
There is no "minus" (-) operator for std::string. You have to use std::string::substr or std::string::erase
If you really want to use - operator, you can overload it.
来源:https://stackoverflow.com/questions/19412698/c-cant-subtract-two-strings