I have tried using cin
in a for
loop, as such
int main() {
int var1, var2, var3;
for (int i = 0; i < 10; i ) {
std::cin >> var1 >> var2 >> var3;
// printf("hi\n");
}
}
when I run the code it only reaches cin
once, and then cin
is no longer called again.
The input should be 10 rows, each of which has 3 integers, such as
1 2 3
4 5 6
7 8 9
...
and so on
If I uncomment the printf("hi\n");
, it will print hi
10 times. Why is this, how can I use cin
in a for
loop correctly. I have tried using scanf
but have reached the same problem.
Thanks!
CodePudding user response:
Thanks everyone for helping, I have figured out the reason. The reason is described by Andreas Wenzel and anastaciu, which was that the input were not integers. Instead of inputting an int for var1, I was inputting a char, but the full code is as shown
int main() {
int var1; int var2; int var3;
for(int i = 0; i < 3; i ) {
std::cin >> var1 >> var2 >> var3;
}
return 0;
}
An example input which would cause an error (still not sure what this specific error is), would result in this output
H 2 3
hi
hi
hi
But using all int as inputs worked fine.
CodePudding user response:
cin in a for loop is correctly
std::cin >> var1 >> var2 >> var3;
but input var1 var2 var3 it's not the same line when you write new line you pass second argument
for example all input this 1 2 3 is var1 it's not (var1 = 1 var2 = 2 var3 = 3)