如何通过我自己的分隔符

时间:2017-05-31 03:37:06

标签: c++ string extract getline istringstream

程序应该将数字输入字符串和数字分隔符作为输入,并在单独的行上输出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: 

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:-1)

cin >> userInfo;将消耗所有空间。

getline(cin, userInfo);将消耗新行字符的所有内容。

我想在你的情况下它并没有什么区别。