-1

The program should take as input the digit infused string and the digit delimiter, and output the 4 words on separate lines.

Example

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

Hint: getline() and istringstream will be helpful.

I'm having trouble finding how/where to use getline() correctly.

Below is my program.

#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;
}

My current output is this

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: 
Marek Vitek
  • 1,573
  • 9
  • 20
Veronica
  • 15
  • 1
  • 3

2 Answers2

0

This is what you have been looking for. Note that getline can take optional third parameter char delim, where you tell it to stop reading there instead of at the end of the line.

#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;
}
Marek Vitek
  • 1,573
  • 9
  • 20
-1

cin >> userInfo; will consume everything up to a space.

Whereas getline(cin, userInfo); will consume everything up to the new line character.

I guess in your case it doesn't make a difference.