2017-05-31 165 views
-1

程序應該將輸入數字的字符串和數字分隔符作爲輸入,並將4個單詞輸出到單獨的行中。如何用我自己的分隔符分割字符串

Please enter a digit infused string to explode: You7only7live7once 
Please enter the digit delimiter: 7 
The 1st word is: You 
The 2nd word is: only 
The 3rd word is: live 
The 4th word is: once 

提示:函數getline()和istringstream會有所幫助。

我很難找到正確使用getline()的方式/位置。

下面是我的程序。

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 
int main() { 
string userInfo; 
cout << "Please enter a digit infused string to explode:" << endl; 
cin >> userInfo; 
istringstream inSS(userInfo); 
string userOne; 
string userTwo; 
string userThree; 
string userFour; 
inSS >> userOne; 
inSS >> userTwo; 
inSS >> userThree; 
inSS >> userFour; 
cout << "Please enter the digit delimiter:" << endl; 
int userDel; 
cin >> userDel; 
cout <<"The 1st word is: " << userOne << endl; 
cout << "The 2nd word is: " << userTwo << endl; 
cout << "The 3rd word is: " << userThree << endl; 
cout << "The 4th word is: " << userFour <<endl; 

return 0; 
} 

我的電流輸出爲這個

Please enter a digit infused string to explode: 
Please enter the digit delimiter: 
The 1st word is: You7Only7Live7Once 
The 2nd word is: 
The 3rd word is: 
The 4th word is: 
+0

輸出'userDel'並告訴我它說了什麼。 :) –

+0

好吧,您不要以任何方式使用您的'userDel',這是有點期待 – Ap31

+0

所以你想知道在哪裏使用你可能甚至不需要的特定功能,而不是實際執行所需的任務?爲什麼? –

回答

-1

cin >> userInfo;會消耗一切都交給一個空間。

getline(cin, userInfo);將消耗一切直到新行字符。

我想你的情況並沒有區別。

+3

是的,但如果利用getline的第三個參數呢? – user4581301

0

這就是你一直在尋找。請注意,getline可以採用可選的第三個參數char delim,您可以告訴它停止閱讀,而不是在行末。

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 
int main() { 
    string userInfo, userOne, userTwo, userThree, userFour; 
    char userDel; 

    cout << "Please enter a digit infused string to explode:" << endl; 
    cin >> userInfo; 
    istringstream inSS(userInfo); 

    cout << "Please enter the digit delimiter:" << endl; 
    cin >> userDel; 

    getline(inSS, userOne, userDel); 
    getline(inSS, userTwo, userDel); 
    getline(inSS, userThree, userDel); 
    getline(inSS, userFour, userDel); 

    cout <<"The 1st word is: " << userOne << endl; 
    cout << "The 2nd word is: " << userTwo << endl; 
    cout << "The 3rd word is: " << userThree << endl; 
    cout << "The 4th word is: " << userFour <<endl; 

    return 0; 
}