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];
}
应该输出数组中的第一个 int,但在输入由空格分隔的数字列表后不输出任何内容(总共少于 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';
}
推荐阅读
- firebase-realtime-database - 如何将分层数据从 Firebase 发送到 Google 工作表
- dataframe - 附加到数据框时,Scrapy Item 不返回 unicode?
- asp.net - ASP.NET,两个 Web.Config
- javascript - 如何在数据表的 ajax 请求的列部分中使用变量
- python - 对列表使用快速排序 >=7000 会导致堆栈溢出
- c# - 如何停止/暂停已在 WPF 上启动的情节提要?
- php - 我在为图像创建单独的表时遇到问题
- puppet - 傀儡代理的公网IP地址
- laravel-envoy - 如何从我的特使脚本将应用程序版本写入数据库?
- c# - 一对文本框中每个字符配对的代码是什么