Reputation: 71
#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];
}
Should output the first int in the array but instead outputs nothing after entering a list of numbers separated by spaces (less than 10 total). Ideally, it should output the entire array but I can't figure out why it won't just output the first value of the array. I suspect it's something to do with while (current >= 0). If so then im wondering how I can check if there are no more inputs left in the stream.
Upvotes: 3
Views: 110
Reputation: 36597
An array such as int grades[10]
in your code cannot be resized in standard C++.
Instead, use a standard container - such as std::vector
- which is designed to be resized at run time
#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';
}
Upvotes: 3