-5

How can i cin an integer then a string "with spaces" this is my code

int x;string s;
    cout<<"Enter Integer"<<endl;
    cin>>x;
    cout<<"Enter the string with spaces"<<endl;
    //if i used cin>>s here then it will not read all the text because it has spaces 
    // is i used getline(cin,s); then it will not read any thing  

2 Answers2

0

The problem you are likely having is that the cin >> x reads only the digits of the number you type, and not the following newline. Then, when you do a cin >> s to read a string, the input processor sees the newline and returns only an empty string.

The solution is to use a function that is designed to read whole lines of input, such as std::getline. Do not use the extraction operator >> for interactive input.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0

To read a string with spaces use std::getline.

But!

Pay attention to what happens with >> when it hits a delimiter. It stops and leaves the delimiter int he stream. This is not a problem so long as you only use >> as >> will discard all of the whitespace. std::getline will capture that whitespace, and a common usecase is

user types in number and hits enter
user types in string and hits enter

So what happens? >> extracts the number and stops when it hits whitespace. This leaves the end of line put in the stream by pressing enter in the stream. std::getline comes along and the first thing it sees is... end of line. std::getline stores an empty string and immediately returns. Now the program processes an empty string and the user, still expecting to type in a string enters a string that will be read by some future read, possibly putting the input stream into an error case and certainly giving the user a surprise.

A common solution is to use ignore(numeric_limits<streamsize>::max(), '\n'); to consume any data still in the stream up to and including the end of line before prompting the user for input and calling std::getline.

Community
  • 1
  • 1
user4581301
  • 33,082
  • 7
  • 33
  • 54