My program jumps right to the end, Neither enters to read.
Follow the code below:
#include <iostream>
int main(void) {
int i= 0;
string nome;
for(i=0;i>=10;++i) {
cin>>nome;
cout<<nome<<endl;
}
}
I can not find the error.
My program jumps right to the end, Neither enters to read.
Follow the code below:
#include <iostream>
int main(void) {
int i= 0;
string nome;
for(i=0;i>=10;++i) {
cin>>nome;
cout<<nome<<endl;
}
}
I can not find the error.
Good friend, as far as I can see, your condition will never be true and you will enter into the bond.
Because of for(i=0;i>=10;++i)
it does not even enter, why i = 0
and you ask i is greater than or equal to 10, then this condition will never be true and will not even enter the loop
You can change by for(i=0;i<=10;++i)
and so it will work properly.
The used operator is wrong, needs to be <
(less than). If you start from 0 and go to 10, and incrementing, you can not verify that the number is greater than a certain value to determine if it will continue. Maybe the confusion is because you did not fully understand how the condition works in for
, it has to be true to keep running, so when it's false it ends the loop of repetition. The correct thing is to check if the number is still less than the desired target value that is 10.
Here you may wonder why it should only be "less than" and not "less than or equal to." Because you started from 0, and you are right to start from this number, it does not make that much difference, the important thing is that it runs 10 times, because that is the problem statement, so you can start from the number you want and go to the appropriate number for this, but it was agreed to start from 0, so the condition is true until the number 9, since 0 counts as well. So the signal must be only smaller, when it equals, or it has reached 10, it must be false, because starting from 0 the number 10 is the eleventh, one more than you want. So the use of <=
is wrong and the accepted and voted answer is wrong.
#include <iostream>
#include <string>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
string nome;
cin >> nome;
cout << nome << endl;
}
}
See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .
As a curiosity I could do this:
for (int i = 1; i <= 10; i++)
Then <=
would be correct because it started from 1, but that's not how programmers do it, getting out of the default creates understanding difficulties. We write codes for everyone to understand and so it is better to follow the standards already adopted.
As it stands, its function will not enter the loop because the variable 'i' starts with a value of 0 and will never meet its condition of being greater than or equal to 10.
for(i=0;i>=10;++i)
So, in fact your code is not in "infinite loop", it just does not go into 'for' and does nothing.
Your operator has the wrong signals, change the line:
for(i=0;i>=10;++i) {
To:
for(i=0;i<10;++i) {