Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't std::noskipws work, or what is it supposed to do?

Tags:

c++

std

cin

First off my understanding is that

cin >> std::noskipws >> str;

should stick a whole line from cin like "i have spaces" into str. However this only puts "i" into str. This could be a false assumption in which case what does std::noskipws do?

I know there is a function std::getline and that does work but simply for educational purposes I decided I would try to get std::noskipws to work for me. I have tried in the past and it just never works so I normally move on and use std::getline.

What I think I have found so far is that std::noskipws technically just unsets std::skipws which internally to the basic_iostream just calls

ios_base::unsetf(std::ios::skipws); 

or

ios_base::unsetf(ios_base::skipws);

So I tried inheriting my own stream form basic_iostream and setting those flags (unsetting) them manually. Still no dice.

So, am I just totally off base or is there a way to make this work?

like image 369
Digital Powers Avatar asked Apr 13 '11 19:04

Digital Powers


People also ask

What does STD Noskipws do?

std::skipws, std::noskipwsEnables or disables skipping of leading whitespace by the formatted input functions (enabled by default).

What does Noskipws mean in C++?

The noskipws() method of stream manipulators in C++ is used to clear the showbase format flag for the specified str stream. This flag reads the whitespaces in the input stream before the first non-whitespace character.


2 Answers

std::noskipws tells the istream to not skip any leading white space when attempting to read a type. When there is no leading white space, then the flag has no impact.

like image 91
Howard Hinnant Avatar answered Sep 24 '22 11:09

Howard Hinnant


std::skipws works as follows: std::istream always keeps a current read position. If std::skipws is set, before operator>> is called the current read position is advanced to the first non-space character.

The behavior you're seeing (stop at the first space after 'i') is caused by operator>> for std::string (and std::wstring). That operator doesn't take the std::istream flags into account. An operator<< for another type may decide otherwise and continue even across spaces.

like image 38
MSalters Avatar answered Sep 23 '22 11:09

MSalters