【发布时间】:2020-11-11 11:01:39
【问题描述】:
插入名称后,然后按 CTRL+D (Unix) 或 CTRL+Z kbd> (Win),程序会提示另一个时间,插入年龄,但事实并非如此。拜托,你能告诉我为什么吗?谢谢。
在这里,我使用此代码中不存在的打印功能的参考。
在线编译https://onlinegdb.com/BkFNcWSgv-下面有相同的代码:↓
#include<string>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const vector<string>& read_names(vector<string> &n) {
for(string temp; cin >> temp;)
n.push_back(temp);
return n;
};
const vector<double>& read_ages(vector<double> &a) {
for(double temp; cin >> temp;)
a.push_back(temp);
return a;
};
int main()
{
vector<string> name;
vector<string>& nn = name;
vector<double> age;
vector<double>& aa = age;
nn = read_names(name);
aa = read_ages(age);
return 0;
}
【问题讨论】:
-
是的,因为您要终止程序。您需要找到其他方法来确定何时开始输入年龄而不是姓名。另外,为什么你们都通过引用传入向量并返回它?你只需要做一个或另一个。
-
@cigien “是的,因为您要终止程序。” 程序是如何终止的?在 Linux 中,Ctrl+D 将 EOF 发送到标准输入。程序继续,但
cin不再阻塞。 -
Ctrl+D 的行为取决于您的终端。我在 VSCode 中尝试过,它似乎关闭了输入流。在我的 Linux 终端中,Ctrl-D 发送 EOF。在
std::cin.clear()之后,我可以读取用户输入。它在 VSCode 和 Tilix 中的行为不同。