gpt4 book ai didi

c++ - 多次从 std::cin 读取——Linux 和 Mac OS X 上的不同行为

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

我想从标准输入中读取一些数字,处理它们,然后读取下一组数字。

我想到了读取 EOF 中的 char 字符并清除 eofbit、failbit 和 badbit 的解决方案。以下代码适用于带有 GCC 4.9.2 的 Ubuntu 14.04:

#include <iostream>
#include <vector>

int main() {
std::vector<double> a;
std::vector<double>::iterator it;
double x;
while(std::cin >> x) {
a.push_back(x);
}
std::cout << "First bunch of numbers:" << std::endl;
for (it = a.begin(); it != a.end(); ++it) {
std::cout << *it << std::endl;
}

// get crap out of buffer
char s;
std::cin >> s;
std::cin.clear();

// go for it again
while (std::cin >> x) {
a.push_back(x);
}
std::cout << "All the numbers:" << std::endl;
for (it = a.begin(); it != a.end(); ++it) {
std::cout << *it << std::endl;
}

return 0;
}

所以,在 Ubuntu 上,我可以输入 1<Return>2<Return>^D ,得到一些输出,输入 3<Return>4<Return>^D ,得到更多输出,然后程序终止。

在 Mac OS 10.10 但是,使用相同的 GCC 版本,程序不会接受第二轮输入,而是在命中 ^D 后两次输出第一个数字序列第一次。

  • 为什么会出现不一致的行为?是否可以解决它?
  • 接受两次输入的惯用方法是什么?
  • 在我的用例中,第一组数字最终可能会从文件或管道中读取。在那种情况下,我如何以交互方式请求额外的输入。

最佳答案

我不是很熟悉,但是这个人有一个类似的问题:Signal EOF in mac osx terminal

By default, OS X (formerly Mac OS X) terminals recognize EOF when control-D is pressed at the beginning of a line.

In detail, the actual operation is that, when control-D is pressed, all bytes in the terminal’s input buffer are sent to the running process using the terminal. At the start of a line, no bytes are in the buffer, so the process is told there are zero bytes available, and this acts as an EOF indicator.

This procedure doubles as a method of delivering input to the process before the end of a line: The user may type some characters and press control-D, and the characters will be sent to the process immediately, without the usual wait for enter/return to be pressed. After this “send all buffered bytes immediately” operation is performed, no bytes are left in the buffer. So, when control-D is pressed a second time, it is the same as the beginning of a line (no bytes are sent, and the process is given zero bytes), and it acts like an EOF.

You can learn more about terminal behavior by using the command “man 4 tty” in Terminal. The default line discipline is termios. You can learn more about the termios line discipline by using the command “man termios”.

Eric Postpischil 接受的答案

我没有 OSX 来测试,但也许这可以解释行为

关于c++ - 多次从 std::cin 读取——Linux 和 Mac OS X 上的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36765617/

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