gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:31:29 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com