Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我可以使用istream_迭代器吗<;char>;要将某些istream内容复制到std::string中?_C++_Stdstring_Istream_Istream Iterator_Input Iterator - Fatal编程技术网

C++ 我可以使用istream_迭代器吗<;char>;要将某些istream内容复制到std::string中?

C++ 我可以使用istream_迭代器吗<;char>;要将某些istream内容复制到std::string中?,c++,stdstring,istream,istream-iterator,input-iterator,C++,Stdstring,Istream,Istream Iterator,Input Iterator,我有一个istream,需要将两个分隔符之间的内容复制到std::string。 我可以找到分隔符'streampos,但是当尝试使用istream\u迭代器在流的部分上进行迭代时,它不起作用。以下是我尝试过的: #include <iostream> #include <sstream> #include <iterator> std::string copyToString( std::istream& is ) { is >&g

我有一个
istream
,需要将两个分隔符之间的内容复制到
std::string
。 我可以找到分隔符'
streampos
,但是当尝试使用
istream\u迭代器
在流的部分上进行迭代时,它不起作用。以下是我尝试过的:

#include <iostream>
#include <sstream>
#include <iterator>


std::string copyToString( std::istream& is )
{
    is >> std::ws;

    auto someLength {10};

    std::istream_iterator<char> beg {is};

    is.seekg( someLength, std::ios::cur );

    //std::istream_iterator<char> end { is };
    std::istream_iterator<char> end { std::next(beg, someLength) };

    return std::string{ beg, end };
}




int main()
{
    std::stringstream ss;
    ss.str( "   { my string content  }" );

    std::cout << "\"" << copyToString( ss ) << "\"\n";

    return 0;
}
#包括
#包括
#包括
std::string copyToString(std::istream&is)
{
is>>std::ws;
自动长度{10};
std::istream_迭代器beg{is};
is.seekg(someLength,std::ios::cur);
//std::istream_迭代器end{is};
std::istream_迭代器end{std::next(beg,someLength)};
返回std::字符串{beg,end};
}
int main()
{
std::stringstream-ss;
str(“{my string content}”);

std::cout
std::istream_迭代器
是一个输入迭代器。输入迭代器是单通道的,当副本增加时无效。当执行
std::next(beg,someLength)
时,读取
someLength
字符。然后
beg
无效

此外,
std::istream_迭代器
不打算计数。由于处理流错误的方式,它被设计为与默认构造的迭代器进行比较。如果尝试计数流错误,则它们有时会再读取一次,具体取决于算法的实现方式


如果您想从输入流中读取
n
字符,只需使用
read
。如果您想跳过空格,只需编写一个循环。如果您想以非预期的方式使用
std::istream\u迭代器
,那么您的代码将无法预料地失败。

fwiw,当我运行代码时,我得到一个segfault
std::next(beg,someLength)
从流中读取10个字符。(但是,我不知道如何正确执行此操作。)@immibis:我相信你弄错了:我对输入流不太确定,但是一旦你做了
seekg
,你不是就让
beg
迭代器失效了吗?我认为这些流的要点是它们在传递完元素后并没有保留它们的元素吗?你可以改为:
std::string result(someLength),;is.read(&result[0],稍长);return result;
谢谢。我不知道这是一个意外的用法,因为这对我来说似乎很基本,而且是迭代器的典型用法。@RL-S是的,至少可以说,输入迭代器受到了很大的限制。但我实际上也尝试了默认构造函数
std::istream\u iterator end;
。为什么不起作用?输出是
>“{”
IIRC。