如何用我自己的分隔符分割字符串

问题描述:

程序应该将输入数字的字符串和数字分隔符作为输入,并将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

所以你想知道在哪里使用你可能甚至不需要的特定功能,而不是实际执行所需的任务?为什么? –

cin >> userInfo;会消耗一切都交给一个空间。

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

我想你的情况并没有区别。

+3

是的,但如果利用getline的第三个参数呢? – user4581301

这就是你一直在寻找。请注意,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; 
}