crashed when using for loop
Jan 17, 2015 at 11:15am UTC
Hello,
I wrote a program to reverse the character order of a string. I could do it with while loop, but it crashed when I used for loop. I know it is about "j >= 0" in the for loop, it did not crash when I used j>0 instead, but it missed the last result.....
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <iostream>
#include <string>
using namespace std;
int main(){
string name;
cout << "Enter a name: " ;
getline(cin, name);
cout << endl;
//for loop for reverse character order
for (unsigned j = (name.size()-1); j >= 0; j--){
cout << name.at(j);
}
cout << endl;
//whlie loop for reverse character order
int j = name.size()-1;
while (j >= 0){
cout << name.at(j);
j--;
}
cout << endl;
}
Jan 17, 2015 at 11:42am UTC
1 2 3
unsigned foo = 0;
foo--;
if ( 0 <= foo ) cout << "oh my" ;
Unsigned 0-1, "-1", is a very big (positive) number. Definitely > 0. You would have an infinite loop, if string::at would not eject.
Try
int
or
1 2 3
for (unsigned j = name.size(); 0 < j; --j ) {
cout << name.at( j-1 );
}
Last edited on Jan 17, 2015 at 11:48am UTC
Topic archived. No new replies allowed.