c++ - 输入迭代器跳过空格,任何防止这种跳过的方法

标签 c++ istream

我正在从一个文件中读取一个字符串,直到我到达一个定界字符,即美元符号。但是输入迭代器正在跳过空格,因此创建的字符串没有空格。在这种情况下不是我想要的。有什么办法可以阻止跳过行为吗?如果是的话怎么办?

这是我的测试代码。

#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.

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

关于c++ - 输入迭代器跳过空格,任何防止这种跳过的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17022096/

相关文章:

c++ - 为什么 std::getline() 在格式化提取后跳过输入?

c++ - C++-标准输入循环

c++ - 处理异常 std::out_of_range C++

c++ - Qt/C++ - 如何从字符串中删除整行?

c++ - 使用共享指针实现单例的正确方法?

c++ - 为每个连接手动分配端口号

STL - 将 istream 中的一行单词转换为 vector 的最简单方法?

c++ - 比较两个 double 的正负

c++ - 在调试或 Release模式下使用 DLL?

C++;镜像并从 std::basic_istream<> 传递?