Как разбить строку по моему собственному разделителю

Программа должна взять в качестве входных данных введенную цифрой строку и разделитель цифр и вывести 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 ответа

Это то, что вы искали. Обратите внимание, что 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); будет потреблять все до новой строки символа.

Я думаю, в вашем случае это не имеет значения.

Другие вопросы по тегам