The C++ manipulator noskipws function is employed to unset the skipws format flag for the str stream.
When the noskipws format flag is enabled, input stream in C++ will not skip any leading whitespace characters before the next input operation. This includes tab spaces, blank spaces, and carriage returns, all of which are treated as whitespace. Consequently, any whitespace encountered will be included as part of the following input field.
This pertains to any formatted input operation executed using the operator >> on the stream.
Syntax
ios_base& noskipws (ios_base& str);
Parameter
str : stream object that is impacted by its format flag.
Return value
It returns argument str.
Data Races
Data races can occur when multiple threads access the same stream object concurrently and make modifications.
Exceptions
If an exception is thrown, the str object remains in a valid state.
Example 1
Let's explore a basic example to showcase the functionality of the noskipws attribute:
#include <iostream> // std::cout, std::skipws, std::noskipws
#include <sstream> // std::istringstream
using namespace std;
int main () {
char a, b, c;
istringstream iss (" 123");
iss >> skipws >> a >> b >> c;
cout << a << b << c << '\n';
iss.seekg(0);
iss >> noskipws >> a >> b >> c;
cout << a << b << c << '\n';
return 0;
}
Output:
123
1
Example 2
Let's see another simple example:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
char first, middle, last;
istringstream("G B S") >> first >> middle >> last;
cout << "Default behavior: First Name = " << first << ", Middle Name = " << middle << ", Last Name = " << last << '\n';
istringstream("G B S") >> noskipws >> first >> middle >> last;
cout << "noskipws behavior: First Name = " << first << ", Middle Name = " << middle << ", Last Name = " << last << '\n';
return 0;
}
Output:
Default behavior: First Name = G, Middle Name = B, Last Name = S
noskipws behavior: First Name = G, Middle Name = , Last Name = B
Example 3
Let's see another simple example:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
char c1, c2, c3;
istringstream("a b c") >> c1 >> c2 >> c3;
cout << "Default behavior: c1 = " << c1 << " c2 = " << c2 << " c3 = " << c3 << '\n';
istringstream("a b c") >> noskipws >> c1 >> c2 >> c3;
cout << "noskipws behavior: c1 = " << c1 << " c2 = " << c2 << " c3 = " << c3 << '\n';
return 0;
}
Output:
Default behavior: c1 = a c2 = b c3 = c
noskipws behavior: c1 = a c2 = c3 = b