2013-10-16 56 views
0

我想在這段代碼中減去兩個字符串,但它不會讓我這樣做,並給出一個運算符 - 錯誤。該代碼基本上試圖將完整的輸入名稱分成兩個輸出:名字和姓氏。請幫忙!謝謝!C++不能減去兩個字符串

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

你可以使用std :: string.substr方法 – taocp

+0

謝謝你的回覆。但我想這樣做是簡單的方法,因爲這個問題在我的測試中,我們沒有涉及到先進的東西。 –

+0

查看您的C++教科書或參考手冊,查看所有可用的運算符與'std :: string'並驗證減法運算符。 –

回答

3

您應該使用std::string::substr。減去這樣的字符串是無效的。

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

第一個參數是要提取的子字符串的起始索引,第二個參數是子字符串的長度。

2

如何定義一個字符串的負運算符?你會從頭開始減去嗎?或者結束?

此外,什麼是"cat" - "dog"?這個操作員沒有意義。

相反,您可能希望使用字符串索引,即employeeName[i],並單獨複製字符,或使用std::string::substrstd::string::erase,正如其他人所建議的那樣。

我會發現substr()最容易,因爲它能夠刪除字符串的部分(在這種情況下,第一個和最後一個名字)。