The influence of noskipws on cin >>

As I understand it, the extraction operator skips the space at the beginning and stops after a collision with a space or the end of the stream. noskipws can be used to stop ignoring leading spaces.

I have the following program in which I used noskipws.

#include <iostream> using namespace std; int main() { char name[128]; cout<<"Enter a name "; cin>>noskipws>>name; cout<<"You entered "<<name<<"\n"; cout<<"Enter another name "; cin>>name; cout<<"You entered "<<(int)name[0]<<"\n"; return 0; } 

My queries are:

  • If I enter "John" as the first input, then the second operation cin → does not wait for input and does not copy anything to the destination, i.e. array of names. I was expecting the second cin -> to pass at least a new line or the end of the stream, instead of just setting an empty destination line. Why is this happening?

  • The same thing happens when you enter "John Smith" as input for the first cin → operator. Why doesn't the second cin → operator copy space or Smith to the target variable?

The following is the output of the program:

 Enter a name John You entered John Enter another name You entered 0 Enter a name John Smith You entered John Enter another name You entered 0 

Thanks!!!

+6
source share
1 answer

The main algorithm for >> string is:

 skip whitespace read and extract until next whitespace 

If you are using noskipws , then the first step is skipped. After the first reading, you fall into spaces, so the next (and all subsequent) reading stops immediately without extracting anything.

>> a string will never fit a space in a string. More generally, using >> with noskipws problematic, since space is always a separator for >> ; it may make sense to use it punctually, but usually it should be reset immediately after using it. (The case where this makes sense is to use >> before char . In this case, the stream always extracts one character.)

+10
source

Source: https://habr.com/ru/post/917609/


All Articles