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