c++ - 如何在不知道最初输入多少值的情况下将整数存储到数组

标签 c++

#include <iostream>
#include<cmath>
using namespace std;

int main(){

int grades[10];
cout << "Enter list: ";

int count = 0;
int current = 0;

while (current >= 0){
  cin >> current;
  grades[count] = current;
  count += 1;
}

cout << grades[0];

}

在输入由空格分隔的数字列表(总共少于 10 个) 后,应输出数组中的第一个整数,但不输出任何内容。理想情况下,它应该输出整个数组,但我不明白为什么它不只输出数组的第一个值。我怀疑这与 while (current >= 0) 有关。如果是这样,那么我想知道如何检查流中是否没有更多输入。

最佳答案

您的代码中的数组,如 int grades[10] 无法在标准 C++ 中调整大小。

相反,使用标准容器 - 例如 std::vector - 设计为在运行时调整大小

#include <vector>
#include <iostream>

int main()
{
      std::vector<int> grades(0);     //   our container, initially sized to zero
      grades.reserve(10);             //   optional, if we can guess ten values are typical

      std::cout << "Enter list of grades separated by spaces: ";
      int input;

      while ((std::cin >> input) && input > 0)   //  exit loop on read error or input zero or less
      {
          grades.push_back(input);    // adds value to container, resizing
      }

      std::cout << grades.size() << " values have been entered\n";

      //   now we demonstrate a couple of options for outputting all the values

      for (int i = 0; i < grades.size(); ++i)   // output the values
      {
           std::cout << ' ' << grades[i];
      }
      std::cout << '\n';

      for (const auto &val : grades)   // another way to output the values (C++11 and later)
      {
           std::cout << ' ' << val;
      }
      std::cout << '\n';
}

关于c++ - 如何在不知道最初输入多少值的情况下将整数存储到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58055874/

相关文章:

c++ - 滥用逗号运算符来柯里化(Currying)函数参数

c++ - 努力实现类型列表

c++ - 如何在终端上以星号(*)的形式显示输入密码

c++ - C++中的宏可以定义宏吗?

C++:创建对象的本地拷贝

c++ - 在 C++ (gcc) 中如何表示 float 和 double?

C++ 文件访问/输入和输出

c++ - Windows 任务管理器确定程序内存使用情况的可靠性如何?

c++ - 当 strlen 用于无符号字符数组和有符号字符数组时发出警告

c++ - 使用异常中止一系列用户输入 - 好吗?坏的?