Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Can't subtract two strings

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;
}
like image 403
Haris Irshad Avatar asked May 25 '26 02:05

Haris Irshad


2 Answers

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.

like image 127
digital_revenant Avatar answered May 27 '26 18:05

digital_revenant


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.

like image 34
khajvah Avatar answered May 27 '26 16:05

khajvah