首页  >  文章  >  后端开发  >  如何使用 C 中的 cin 将多个用户输入存储在向量中?

如何使用 C 中的 cin 将多个用户输入存储在向量中?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-28 18:02:02747浏览

How can I store multiple user inputs in a vector using cin in C  ?

使用 cin 将用户输入存储在向量中

在 C 中,向量是可以存储相同类型元素的动态数组。要将用户输入存储在向量中,可以使用 cin 流对象。但是,考虑所提供代码的局限性非常重要。

理解提供的代码

给定的代码尝试从用户读取数字并将其存储在向量。但是,它仅捕获输入的第一个数字。要解决这个问题,需要一个循环来连续接受多个整数。

解决方案

以下代码的修改版本:

<code class="cpp">int main() {
  int input;
  vector<int> V;
  cout << "Enter your numbers to be evaluated: " << endl;

  // Use a loop to read multiple integers from cin
  while (cin >> input)
    V.push_back(input);

  write_vector(V);
  return 0;
}</code>

通过利用循环,此更新的代码会读取数字,直到用户按下 Ctrl D (Linux/Mac) 或 Ctrl Z (Windows)。每个输入的数字都会添加到向量中。

其他注意事项

另一种方法涉及使用标记值。这允许使用特定值来表示输入结束,如下所示:

<code class="cpp">int main() {
  int input;
  vector<int> V;
  cout << "Enter numbers (enter -1 to stop): " << endl;

  // Use a sentinel value to terminate input
  while (cin >> input && input != -1)
    V.push_back(input);

  write_vector(V);
  return 0;
}</code>

在这种情况下,输入“-1”将停止用户输入并终止循环。

以上是如何使用 C 中的 cin 将多个用户输入存储在向量中?的详细内容。更多信息请关注PHP中文网其他相关文章!

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