Overclock.net banner

1 - 8 of 8 Posts

·
Premium Member
Joined
·
10,858 Posts
Discussion Starter #1
How would I go about breaking a loop if the escape key is pressed. I'm using devc++ within windows. So far I have tried something like this but it doesn't work.

Code:

Code:
#include<conio.h>
char cIn;
while((cIn = getch()) != 27)
//random
//coding
Halp.
 

·
Registered
Joined
·
579 Posts
Code:

Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string button;
getline(cin,button);
while(button != "(backslash)0"){  // for some reason the forum edits out the backslash zero part.
getline(cin,button);
cout << "lolz" << endl;
}
system("PAUSE");
}
yep. and i have no idea why are u using the backspace character ← in ur code.
 

·
Premium Member
Joined
·
10,858 Posts
Discussion Starter #3
Quote:

Originally Posted by newbie1911 View Post

Code:

Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string button;
getline(cin,button);
while(button != "(backslash)0"){  // for some reason the forum edits out the backslash zero part.
getline(cin,button);
cout << "lolz" << endl;
}
system("PAUSE");
}
yep. and i have no idea why are u using the backspace character ← in ur code.
That code doesn't seem to be working for me and I didn't even know I had the backspace character in my original code. It's supposed to look like this right?
LL
 

·
Premium Member
Joined
·
10,858 Posts
Discussion Starter #4
I think I got it to work...

Code:

Code:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    char cIn;

    while((cIn = getch()) != 27)
    cout << "POTATOESn";

    system("PAUSE");
}
I'll just have to try it with my real code later.
 

·
Registered
Joined
·
130 Posts
Quote:

Originally Posted by Kuntz View Post
break;
continue;

Those two keywords will help you out a lot in loop programming.
Yup - if you structure your code to avoid the need to use either of them then it will be infinitely more maintainable in the long run
 

·
Registered
Joined
·
130 Posts
Quote:

Originally Posted by newbie1911 View Post
I was wrong. it exits on the enter key and not the escape key.
It exits the loop on input of an empty string, so yes, hitting the enter key will cause it to terminate the loop, but not because it's reading a CR but because the input buffer contains only the null character.

As an aside, note that cin.getline() reads all characters until it encounters the newline character. If that happens, the new line character is cleared from the input stream but is NOT stored in your ntca-variable.

On the other hand, cin >> skips over blanks and new lines and leaves them in the input stream. Therefore, mixing cin >> with .getline() is dangerous. So if you use .getline() after cin>> you should manually clear the input stream of any possible undesired left-over input.
 
1 - 8 of 8 Posts
Top