Can't exit of of while loop
Aug 18, 2015 at 2:46am UTC
In the code below I have 3 while loops and I was to use the letter "q" to exit the loop. When testing out the first while loop, I am able to exit the loop fine when pressing typing in "q". However, the other 2 are stuck in an infinite loop and I'm not sure how to exit it.
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 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
void make_word_uppercase(string& s){
for (int i = 0; i < s.size(); ++i){
s[i] = toupper(s[i]);
}
}
int main() {
string word = "" ;
// This Works
while (cin >> word){
if (word == "q" ){
break ;
} else {
make_word_uppercase(word);
cout << word;
}
}
// I enter q and it still keeps going
while (word != "q" && cin >> word){
make_word_uppercase(word);
cout << word;
}
// Same as above
while (word != "q" ){
cin >> word;
make_word_uppercase(word);
cout << word;
}
}
Last edited on Aug 18, 2015 at 2:47am UTC
Aug 18, 2015 at 3:07am UTC
return 0;
Aug 18, 2015 at 3:14am UTC
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 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
void make_word_uppercase(string& s){
for (unsigned int i = 0; i < s.size(); ++i){
s[i] = toupper(s[i]);
}
}
int main() {
string word = "" ;
// This Works
while (cin >> word){
if (word == "q" ){
break ;
} else {
make_word_uppercase(word);
cout << word;
}
}
while (cin >> word && word != "q" ){ //change order of test
make_word_uppercase(word);
cout << word;
}
while (word != "Q" ){
cin >> word;
// this changes it to Q and thus will keep going if tested for q
make_word_uppercase(word);
cout << word;
}
return 0;
}
Aug 18, 2015 at 3:17am UTC
Thanks for the help.
Topic archived. No new replies allowed.