C++ Can't subtract two strings

28,631

Solution 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.

Solution 2

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.

Solution 3

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).

Share:
28,631
Haris Irshad
Author by

Haris Irshad

Updated on October 18, 2020

Comments

  • Haris Irshad
    Haris Irshad over 3 years

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