Entering an iterator skipping spaces, any way to prevent this skipping

I read from the file to the line until I get to the separator character, the dollar sign. But the input iterator skips spaces, so the generated string has no spaces. not what i want in this case. Is there any way to stop skipping behavior? And if so, how?

Here is my test code.

#include <iostream> #include <fstream> #include <iterator> #include <string> // istream iterator is skipping whitespace. How do I get all chars? void readTo(std::istream_iterator<char> iit, std::string& replaced) { while(iit != std::istream_iterator<char>()) { char ch = *iit++; if(ch != '$') replaced.push_back(ch); else break; } } int main() { std::ifstream strm("test.txt"); std::string s; if(strm.good()) { readTo(strm, s); std::cout << s << std::endl; } return 0; } 
+6
source share
1 answer

Since streams are configured by default to skip spaces, so use

 noskipws(strm); 

Standard:

basic_ios constructors

explicit basic_ios(basic_streambuf<charT,traits>* sb);

Effects: Creates an object of the basic_ios class, assigning initial values ​​to its member objects, calling init(sb).

basic_ios();

Effects: Creates an object of the basic_ios class (27.5.2.7), leaving its member objects uninitialized. An object must be initialized by calling its init member function. If it is destroyed before it was initialized undefined behavior.

[...]

void init(basic_streambuf<charT,traits>* sb);

Postconditions: postconditions of this function are indicated in table 118.

 +----------+-------------+ | ... | ... | | flags() | skipws|dec | | ... | ... | +----------+-------------+ (Table 118) 
+12
source

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


All Articles