Beside all other problems, the main problem is here:
for(int i =0; i!=999; i++){
cin >> numbers[i];
}
You are reading from the standard input into the i-th element of the array numbers
. You are comparing i
with 999, which basically makes no sense. Why comparing i
? And why comparing it with 999, instead of -999?
Let's try to fix it. Start with an empty infinite loop:
while (true) {
// Read
// Check
// Use
}
Read an integer:
while (true) {
// Read
int val;
cin >> val;
// Check
// Use
}
Now let's check if we managed to read something and if not let's exit from the loop.
while (true) {
// Read
int val;
cin >> val;
// Check
if (cin.fail()) {
break;
}
// Use
}
We need to exit from the loop also if we read a -999:
while (true) {
// Read
int val;
cin >> val;
// Check
if (cin.fail()) {
break;
}
if (val == -999) {
break;
}
// Use
}
Now you want to put it in the i-th position of numbers, so:
int i = 0;
while (true) {
// Read
int val;
cin >> val;
// Check
if (cin.fail()) {
break;
}
if (val == -999) {
break;
}
// Use
numbers[i] = val;
++i;
}
Ok, now we have a working loop (hopefully). What other problems you have in your code?
- int numbers[] = {};
- j<=sizeof(numbers)
You cannot define arrays without a compile time size in C++. Use std::vector<>
.
Then, the sizeof
operator doesn't do what you think it does. Save it for (much?) later. Use std::vector::size()
. But for starters, you can assume that 1000 numbers will be enough for everyone (Bill Gates docet), and keep the count in variable i
:
#include <iostream>
using namespace std;
int main()
{
cout << "Enter values. Use -999 to stop entering values.\n";
int numbers[1000]; // We accept 1000 numbers at most
int i = 0;
while (true) {
// Read
int val;
cin >> val;
// Check
if (cin.fail()) {
break;
}
if (val == -999) {
break;
}
// Use
numbers[i] = val;
++i;
}
cout << "Your numbers are: ";
for (int j = 0; j < i; j++) {
cout << numbers[j] << " ";
}
cout << '\n';
return 0;
}
Switching to std::vector<>
is much better. And learn Why is "using namespace std;" considered bad practice?:
#include <iostream>
#include <vector>
int main()
{
std::cout << "Enter values. Use -999 to stop entering values.\n";
std::vector<int> numbers;
while (true) {
// Read
int val;
std::cin >> val;
// Check
if (std::cin.fail()) {
break;
}
if (val == -999) {
break;
}
// Use
numbers.push_back(val);
}
std::cout << "Your numbers are: ";
for (int j = 0; j < numbers.size(); j++) {
std::cout << numbers[j] << " ";
}
std::cout << '\n';
return 0;
}
Finally, if you think that while(true) {}
is ugly, you can use other versions of the same loop, e.g.:
for (int val; std::cin >> val && val != -999;) {
numbers.push_back(val);
}