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;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With