首页 > 解决方案 > 如何在不知道最初输入多少值的情况下将整数存储到数组中

问题描述

#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];

}

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

标签: c++

解决方案


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';
}

推荐阅读