indigoshift
January 29th, 2007, 07:34 PM
Time for a little CompSci 101. ;)
I've been playing around with C++ again, and wrote this quick little program to see if I could remember how to do a "do/while" loop:
// do/while loop
#include <iostream>
#include <string>
using namespace std;
bool repeat = false;
int main()
{
string x;
do{
cout << "enter text: ";
getline(cin,x);
cout << "you entered: " << x << endl;
cin.clear();
cout << "again (1/0)? ";
cin >> repeat;
}while(repeat);
return 0;
}
It'll work fine the first time through. The second time, though, it'll ask for input, then it'll just run itself to death in an endless loop, like so:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
.
.
.
(and so on and so forth...forever)
I stuck a "cin.clear();" in there, and that lets it run right twice before the endless loop.
So am I screwing up the getline or the do/while? I'm assuming the getline is where things are breaking, since I've changed to do/while to a while() loop, and even tried the dreaded goto as alternatives. Both gave the same results. It's very weird.
I've been playing around with C++ again, and wrote this quick little program to see if I could remember how to do a "do/while" loop:
// do/while loop
#include <iostream>
#include <string>
using namespace std;
bool repeat = false;
int main()
{
string x;
do{
cout << "enter text: ";
getline(cin,x);
cout << "you entered: " << x << endl;
cin.clear();
cout << "again (1/0)? ";
cin >> repeat;
}while(repeat);
return 0;
}
It'll work fine the first time through. The second time, though, it'll ask for input, then it'll just run itself to death in an endless loop, like so:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
again (1/0)? enter text: you entered:
.
.
.
(and so on and so forth...forever)
I stuck a "cin.clear();" in there, and that lets it run right twice before the endless loop.
So am I screwing up the getline or the do/while? I'm assuming the getline is where things are breaking, since I've changed to do/while to a while() loop, and even tried the dreaded goto as alternatives. Both gave the same results. It's very weird.