繁体   English   中英

程序终止前开始第二个输入 stream

[英]Program terminates before to start the second input stream

插入姓名后,然后按CTRL + D (Unix) 或CTRL + Z (Win) 终止输入 stream,程序会提示另一个时间,插入年龄,但事实并非如此。 拜托,你能告诉我为什么吗? 谢谢。

在这里,我使用此代码中不存在的打印 function 的参考。

在线编译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;
}

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

在我的 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM