微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/c/113665.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐