Reputation: 525
As you can see from title I am trying to input numbers unless I enter number 0. The problem that I have is that I am entering numbers in for loop and with array. The actual problem with that is that I am entering the numbers unless the "i" reaches the number 100 (as you can see from the code). Even if I enter the number 0, it doesnt do nothing. I am beginner at C++, so if you are not understanding the code or I am going in the completely wrong way with this, please help me.
#include <iostream>
using namespace std;
int main() {
int n;
int number[100];
for (int i = 0; i < 100; i++)
{
if (number[i] != 0)
cin >> number[i];
}
cout << "Enter number n: ";
cin >> n;
for (int i = 0; i < 100; i++)
{
if (number[i] % n == 0)
cout << number[i];
}
return 0;
}
The output is the just entering numbers, like I said in the beggining. P.S:I can use whatever I want (vectors,functions...)
Upvotes: 0
Views: 137
Reputation: 122133
Not sure if I interpret your code correctly, but you have the logic reversed:
for (int i = 0; i < 100; i++)
{
if (number[i] != 0)
cin >> number[i];
}
Here you check for 0
before you read user input. Instead you should first read input and only then check if it was 0
(and you should never try to access something before it is initialized, as is the case for your number
array).
For dynamically sized arrays you can use std::vector
:
std::vector<int> numbers;
int number;
while ( std::cin >> number && number != 0) {
numbers.push_back(number);
}
This will also stop when the user entered something that cannot be read as int
and after that loop numbers.size()
tells you how many numbers have been entered.
Upvotes: 1
Reputation: 409166
A major problem is the check you have:
if (number[i] != 0)
It's a major problem because it's done before you initialize anything in number[i]
, when its value is indeterminate. And using indeterminate values lead to undefined behavior in your program.
If you want to skip zeroes in the input, you need to read into a temporary variable, and check if that value is zero or not.
You also need to keep track of the number of values you have input in a different way, since zeroes should not be counted.
Perhaps something like this:
size_t count = 100;
// Loop while we have still have numbers to input
while (count > 0)
{
int temp;
// Read a number from the user
std::cin >> temp;
// If it's not zero, then add it to the array, else just ignore it
if (temp != 0)
{
// 100 - count will result in the index where the number is added to the array
input[100 - count] = temp;
// One less number to read
--count;
}
}
There are of course better solutions than the one shown above, but it should hopefully be clearer, as well as don't use anything you might not have been taught yet.
Upvotes: 1