Issues with 'for' loop..

I have been working on this problem for at least an hour.
"First, read in an input value for variable numIn. Then, read numIn integers from input and output each integer on a newline after the string "quantity-"."

The code I made seems to work OK except it prints the last input a million times.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main() {
   int numIn;
 
 
cin >> numIn;
 for (int i = 0; i < numIn; i++) {
        cin >> numIn;
        cout << "quantity-" << numIn << endl;
    }
 
   return 0;
}
You're mutating the numIn variable as you loop.
Have two different variables: numIn (number of subsequent inputs), then another variable just called "input" or something. This is the variable you will fill in each iteration within the loop.

1
2
3
4
5
for (int i = 0; i < numIn; i++) {
    int quantity;
    cin >> quantity;
    cout << "quantity-" << quantity << endl;
}
Last edited on
Thank you so much, that solved some of the problems. Now it's telling me
"Program generated too much output.
Output restricted to 5000 characters.

Check program for any unterminated loops generating output."
And printed out 25 a TON of times.
What input value have you used?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
include <iostream>

int main() {
    int numIn {};

    std::cin >> numIn;

    for (int i = 0; i < numIn; ++i) {
        int quantity {};

        std::cin >> quantity;
        std::cout << "quantity- " << quantity << '\n';
    }
}



5
1 2 3 4 5
quantity- 1
quantity- 2
quantity- 3
quantity- 4
quantity- 5


Note that there is no checking for invalid values (particularly numIn).

It's also good practice to initialise variables as they are defined. If they are not, then there value is undetermined until they have been assigned a value. In the OP code above, if the >> numIn fails because a non-number is entered, then the value of numIn is not known - and so the loop could execute for an unknown number of times. In such cases the cin >> quantity would fail so the value of quantity would also be unknown. Hence it's possible to get extraneous unwanted output when variables aren't initialised.

In the OP code above, if the >> numIn fails because a non-number is entered, then the value of numIn is not known
Just so you know, it is guaranteed to be zero-assigned if >> fails, as of C++11 retroactively applied to C++98*.

*I wouldn't necessarily trust a C++98 compiler due to the defect report (linked below).
It doesn't hurt to be safe I guess if working with a really old compiler.

https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
if extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set.

If it's signed underflow/overflow, then it writes the min/max possible value instead of 0.
If it's unsigned underflow/overflow, then it writes the max possible value.
Last edited on
Topic archived. No new replies allowed.