c – 输入迭代器跳过空格,以任何方式防止这种跳过

前端之家收集整理的这篇文章主要介绍了c – 输入迭代器跳过空格,以任何方式防止这种跳过前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在从一个文件读取一个字符串,直到我达到一个分隔字符,美元符号.但输入迭代器正在跳过空格,因此创建的字符串没有空格.在这种情况下不是我想要的.有没有办法阻止跳绳行为?如果是这样怎么样?

这是我的测试代码.

#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;
}

解决方法

因为默认情况下将流配置为跳过空格,所以请使用
noskipws(strm);

标准:

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.

06001

原文链接:https://www.f2er.com/c/113665.html

猜你在找的C&C++相关文章