【问题标题】:Program terminates before to start the second input stream程序在开始第二个输入流之前终止
【发布时间】: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 中的行为不同。

标签: c++ vector reference


【解决方案1】:

Ctrl+D 的行为取决于您的终端。我在 VSCode 中尝试过,它似乎关闭了输入流。我无法重新打开它。

在我的 Linux 终端 (Tilix) 中,Ctrl-D 发送 EOF。在std::cin.clear() 设置后,goodbit 可以再次读取用户输入。 https://en.cppreference.com/w/cpp/io/ios_base/iostate

它在 VSCode 和 Tilix 中的行为不同。

以下代码对我有用。我不知道 Windows、Mac 或其他操作系统中的行为。

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

const std::vector<std::string>& read_names(std::vector<std::string>& n) {
  for (std::string temp; std::cin >> temp;) n.push_back(temp);
  return n;
}

const std::vector<double>& read_ages(std::vector<double>& a) {
  for (double temp; std::cin >> temp;) a.push_back(temp);
  return a;
}

int main() {
  std::vector<std::string> name;
  std::vector<std::string>& nn = name;

  std::vector<double> age;
  std::vector<double>& aa = age;

  //std::cout << std::cin.rdstate() << '\n';
  nn = read_names(name);
  //std::cout << std::cin.rdstate() << '\n';
  std::cin.clear();
  //std::cout << std::cin.rdstate() << '\n';
  aa = read_ages(age);

  std::cout << nn.size() << '\n';
  std::cout << aa.size() << '\n';
  //std::cout << std::cin.rdstate() << '\n';
  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多