Tyler-student
Tyler-student

Reputation: 3

How to read user input with delimiting character while retaining white spaces as input in c++

I'm stuck on processing user input in the manor that is required. I need to take input for example "Name100/Some other name". With the code I have below I can assign everything up to the '/' to the variable input1, however I cannot get the entire string 'Some other name' into the variable input2, only the first word is assigned. Thank you for your help.

string input;
string input1;
string input2;

cout << "Please enter a Name and Another Name" << endl;     
cin >> input;

stringstream ss(input);
getline(ss, input1, '/');
getline(ss, input2);

cout << input1 << endl;
cout << input2 << endl;

Output:

Please enter a Name and Another Name

Name100

Some

Upvotes: 0

Views: 55

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Instead of

cin >> input;

use

std::getline(std::cin, input);

The first will stop reading at the first white space character. The second will read the entire line.

Upvotes: 2

Related Questions