Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;Can';t减去两个字符串_C++_String_Operator Keyword_Subtraction - Fatal编程技术网

C++ C++;Can';t减去两个字符串

C++ C++;Can';t减去两个字符串,c++,string,operator-keyword,subtraction,C++,String,Operator Keyword,Subtraction,我想在这段代码中减去两个字符串,但它不允许我这样做,并给出了一个运算符错误。这段代码基本上试图将完整的输入名分为两个输出:名字和姓氏。请帮忙!谢谢大家! #include <iostream> #include <cstdlib> #include <string> using namespace std; string employeeName, firstName, lastName; int pos1, difference; int main()

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

#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;
字符串employeeName、firstName、lastName;
int-pos1,差异;
int main(){

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

firstName = employeeName.substr(0, employeeName.find(" "));
第一个参数是要提取的子字符串的起始索引,第二个参数是子字符串的长度。

没有“减号”()运算符。必须使用或


如果您真的想使用-operator,可以重载它。

如何定义字符串的减号运算符?是从开头减法还是从结尾减法

此外,什么是“猫”-“狗”
?这个操作符没有意义

相反,您可能希望使用字符串索引,即
employeeName[i]
,并单独复制字符,或者像其他人建议的那样使用
std::string::substr
std::string::erase


我认为
substr()
是最简单的,因为它能够删除字符串的各个部分(在本例中是名字和姓氏)

你可以使用STD::String。String方法谢谢你。但是我想做简单的方法,因为这个Q是在我的测试中,我们还没有覆盖高级的东西。看看你的C++教科书或参考书,看看所有可用的运算符都有<代码> STD::String < /Cord>并验证减法运算符。注意<代码>字符串::擦除
修改输入字符串,因此即使
firstName=employeeName-lastName
有效,名字已经从
employeeName
中删除。谢谢Jonathan!!这真的很有帮助!!!