首页  >  文章  >  后端开发  >  将用户输入存储到向量中时,为什么只计算第一个数字?

将用户输入存储到向量中时,为什么只计算第一个数字?

Patricia Arquette
Patricia Arquette原创
2024-10-26 12:01:29512浏览

Why is only the first number being counted when storing user input into a vector?

将用户输入存储到向量中:综合指南

在此查询中,用户尝试将多个数字输入到向量中,并且随后使用函数调用对它们进行计数。下面提供的代码存在仅计算第一个数字的问题:

<code class="cpp">template <typename T>
void write_vector(const vector<T>&amp; 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;
}</code>

罪魁祸首在于当前仅从用户读取单个整数。为了解决这个问题,需要一个循环。

<code class="cpp">while (cin >> input)
    V.push_back(input);</code>

此循环不断从标准输入中检索整数,直到没有更多可用的输入。当 cin 检测到文件结尾 (EOF) 或遇到非整数值时,输入过程结束。

或者,可以使用哨兵值,其缺点是阻止用户输入该特定值。例如:

<code class="cpp">while ((cin >> input) && input != 9999)
    V.push_back(input);</code>

在此场景中,将收集输入,直到用户输入 9999(或触发另一个使 cin 无效的条件),此时循环终止。

以上是将用户输入存储到向量中时,为什么只计算第一个数字?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn