如何将 cin 值转换为向量 [英] How to cin values into a vector

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

问题描述

我试图让用户输入将被推入向量中的数字,然后使用函数调用来计算这些数字.

I'm trying to ask the user to enter numbers that will be pushed into a vector, then using a function call to count these numbers.

为什么这不起作用?我只能数第一个数字.

why is this not working? I'm only able to count 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 中拉取整数;循环继续,直到 cin 找到 EOF 或尝试输入非整数值.另一种方法是使用标记值,尽管这会阻止您实际输入该值.例如:

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(或任何其他导致 cin 无效的状态),此时循环将终止.

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天全站免登陆