input iterator skipping whitespace, any way to prevent this skipping

别来无恙 提交于 2019-12-12 10:44:18

问题


I am reading from a file into a string until I reach a delimitting character, the dollar symbol. But the input iterator is skipping whitespace so the string created has no spaces. not what I want in this case. Is there any way to stop the skipping behaviour? 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;
}

回答1:


Because streams are by default configured to skip whitespace, therefore, use

noskipws(strm);

Standard:

basic_ios constructors

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

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

basic_ios();

Effects: Constructs an object of class basic_ios (27.5.2.7) leaving its member objects uninitialized. The object shall be initialized by calling its init member function. If it is destroyed before it has been initialized the behavior is undefined.

[...]

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

Postconditions: The postconditions of this function are indicated in Table 118.

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


来源:https://stackoverflow.com/questions/17022096/input-iterator-skipping-whitespace-any-way-to-prevent-this-skipping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!