如何用自己的定界符分开字符串
How to split string by my own delimiter
该程序应作为输入数字注入的字符串和数字定界符,然后在单独的行上输出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:
这就是您一直在寻找的。请注意,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;
}
cin >> userInfo;
将把所有东西都放在一个空间中。
getline(cin, userInfo);
将把所有内容都耗尽到新的行字符。
我想在您的情况下,这没有什么区别。