如何cin到矢量 [英] How to cin to a vector

查看:141
本文介绍了如何cin到矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要求用户输入一个向量中的数字,
然后使用函数调用cout数字,为什么这不是
工作?我只能处理第一个数字。

I'm trying to ask the user to enter numbers thats put into a vector, then using a function call to cout the numbers, why is this not working? I am only able to cout the first number.

template <typename T>
void write_vector(const vector<T>& V)
{
   cout << "The numbers in the vector are: " << endl;
  for(int i=0; i < V.size(); i++)
    cout << V[i] << " ";
}

int main()
{
  int input;
  vector<int> V;
  cout << "Enter your numbers to be evaluated: " << endl;
  cin >> input;
  V.push_back(input);
  write_vector(V);
  return 0;
}


推荐答案

只读取一个整数并将其推入您的向量。因为你可能想存储几个整数,你需要一个循环。例如,替换

As is, you're only reading in a single integer and pushing it into your vector. Since you probably want to store several integers, you need a loop. E.g., replace

cin >> input;
V.push_back(input);

while (cin >> input)
    V.push_back(input);

这样做只要有输入就可以继续从cin中提取int。循环继续,直到cin找到EOF或尝试输入非整数值。替代方法是使用sentinel值,虽然这会阻止您实际输入该值。例如:

What this does is continually pull in ints from cin for as long as there is input to grab; the loop continues until cin finds EOF or tries to input a non-integer value. The alternative is to use a sentinel value, though this prevents you from actually inputting that value. Ex:

while ((cin >> input) && input != 9999)
    V.push_back(input);

将读取,直到您尝试输入9999(或任何其他状态,此时循环将终止。

will read until you try to input 9999 (or any of the other states that render cin invalid), at which point the loop will terminate.

这篇关于如何cin到矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆