gpt4 book ai didi

c++ - 修改和非修改 putback() 之间的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:29 25 4
gpt4 key购买 nike

问题来自https://en.cppreference.com/w/cpp/io/basic_istream/putback , 示例代码。

#include <sstream>
#include <iostream>

int main()
{
std::istringstream s2("Hello, world"); // input-only stream
s2.get();
if (s2.putback('Y')) // cannot modify input-only buffer
std::cout << s2.rdbuf() << '\n';
else
std::cout << "putback failed\n";

s2.clear();
if (s2.putback('H')) // non-modifying putback
std::cout << s2.rdbuf() << '\n';
else
std::cout << "putback failed\n";
}

为什么 s2.putback('Y') 失败但 s2.putback('H') 成功?后者不也是修改input-only stream buffer的操作吗?


此外,我在做一些实验时发现了一些令人困惑的事情。与上面的示例相比,我添加了 1 行代码,但第二个结果失败了。这是为什么?

#include <sstream>
#include <iostream>

int main()
{
std::istringstream s2("Hello, world"); // input-only stream
s2.get();
if (s2.putback('Y')) // cannot modify input-only buffer
std::cout << s2.rdbuf() << '\n';
else
std::cout << "putback failed\n";

std::cout << s2.rdbuf() << '\n'; //1 line code added

s2.clear();
if (s2.putback('H')) // non-modifying putback
std::cout << s2.rdbuf() << '\n';
else
std::cout << "putback failed\n";

}

最佳答案

Why s2.putback('Y') fails but s2.putback('H') succeed? Isn't the latter also an operation to modify the input-only stream buffer?

调用 s2.putback('H') 可能 修改缓冲区,但在这种情况下,它不会,因为数据已经以 'H'.

你可以举例说明这样的行为:

s2.clear();

assert(s2.putback('H')); // Ok, replacing 'H' with 'H' doesn't change anything
assert(!s2.putback('Z')); // Can't modify.

关于c++ - 修改和非修改 putback() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52362361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com