我想在这段代码中减去两个字符串,但它不允许我这样做,并给出一个运算符-错误。这段代码基本上试图将一个完整的输入名称分为两个输出:名字和姓氏。请帮忙!谢谢!

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

最佳答案

您应该使用std::string::substr。减去这样的字符串是无效的。

firstName = employeeName.substr(0, employeeName.find(" "));

第一个参数是要提取的子字符串的起始索引,第二个参数是子字符串的长度。

09-06 10:33