how do you take in the enter key as an input? - c++

I have been trying to take the enter key in as an input for my program. I have defined a char ENTER variable and used cin >> ENTER; to take in the enter key. Then I have used an if statement to determine whether the Enter key was press. if(ENTER == '13'), '13' is the ascii code for enter. It doesn't seem to be working, any suggestions?

How to detect the Enter Key without corrupting valid input:
char c;
cin.get(c); // get a single character
if (c == 10) return 0; // 10 = ascii linefeed (Enter Key) so exit
else cin.putback(c); // put the character back and proceed normally
Alternatively:
char c;
c = cin.peek(); // read next character without extracting it
if (c == '\n') return 0; // linefeed (Enter Key) so exit

Related

How to bail out of a while loop once a certain value is inputted into a variable

I'm making a program that uses a while loop in C++. Here is my code so far:
int userInput = 0;
while (userInput != 'Z')
{
cout << "Please enter the homework score: ";
cin >> userInput;
homeworkScores.push_back(userInput);
if (userInput == 'Z') {
userInput = 'Z';
}
}
The problem im having is whenever I type Z, the loop keeps printing "Please enter the homework score: " over and over without stopping. I've defined homeworkScores as a vector earlier in the code. How can I make it stop the loop once userInput == 'Z'? Thanks in advance!
The problem you are facing, is that cin is trying to read an integer, but you provide a character in the input. cin will only ask for another input, once the input is empty, you can try this by supplying more than one integer to your code:
Please enter the homework score: 2 27 12 8
will input all four numbers and print "Please enter the homework score: " 4 additional times.
If you provide it with a character, it will not remove it from the input, so whenever "cin" is reached, it will see "Z" in the input, and continue.
You can use answers like provided here How to catch invalid input in c++? for your input sanitation, but it will not make "Z" work as a stop.
The easiest way is to chose an invalid score like -1 instead of Z, end on any invalid input or try to read a string on failure to read an int.
A simple way to exit a loop is by using the break statement.
if (userInput == 'Z') {
userInput = 'Z';
break;
}
Other ways would be to set your exit condition to resolve as false, which I think is causing some issues for you.
EDIT: As #Ganea Dan Andrei noted, reading a char from cin into an integer will cause the cin::fail() to return true. This can be reset by calling cin.clear(), which will allow you to make further inputs.
userInput is an integer, and so 'Z' would have to equal the ASCII equivalent of its char value, which is 90. The way you're doing it should shouldn't work. Instead, try making userInput a char, and then convert it to an integer so you can push it back into your vector. This might look like:
char userInput = '';
while (userInput != 'Z')
{
cout << "Please enter the homework score: ";
cin >> userInput;
homeworkScores.push_back(userInput - '0'); //Are you sure you want to push a 'Z'?
if (userInput == 'Z') {
userInput = 'Z';
break;
}
userInput = ''; // Reset your input so it doesn't keep getting pushed new values
}
What happens here is userInput - '0' is subtracting the ASCII values of your chars, and leaving you with their integer value. There are other ways to do this, but this is a commonly used way.

Extra letter being displayed in Password Field

void createAccount(){
int i=0;
cout<<"\nEnter new Username: ";
cin.ignore(80, '\n');
cin.getline(newUsername,20);
cout<<"\nEnter new Password: ";
for(i=0;i<10,newPassword[i]!=8;i++){
newPassword[i]=getch(); //for taking a char. in array-'newPassword' at i'th place
if(newPassword[i]==13) //checking if user press's enter
break; //breaking the loop if enter is pressed
cout<<"*"; //as there is no char. on screen we print '*'
}
newPassword[i]='\0'; //inserting null char. at the end
cout<<"\n"<<newPassword;
}
In function createAccount(); the user is entering char newUsername[20] and char newPassword[20]. However, to display the password as ****** I've implemented a different way for entering newPassword. However, when I try displaying newPassword the output has an extra letter that magically appears in the command box without me entering anything.
OUTPUT
Enter new Username: anzam
Enter new Password: ****** //entered azeez but the first * is already there in command box without user inputting anything
Mazeez //displaying newPassword
If someone could help me I'd be extremely grateful.
One problem might be that you intermix conio (getch) and iostream (cin), and they might not be synchronized. Try adding this line at the beginning of your program:
ios_base::sync_with_stdio ();
Also, you read password until you see 13, but, if I'm not mistaken, in reality in windows pressing enter produces first 10 and then 13, so you might want to check for both as a stop condition.
i has been incremented at the end of the loop. The easiest way to fix this is to initialize password to zero
char newPassword[20];
memset(newPassword, 0, 20);
for (i = 0; i < 10; )
{
int c = getch();
if (c == 13)
break;
//check if character is valid
if (c < ' ') continue;
if (c > '~') continue;
newPassword[i] = c;
cout << "*";
i++; //increment here
}

while loop and getchar()

I have the simple program below that I wrote for a college course. I know it doesn't really do anything, but it's just an assignment for a course.
The part that I can't figure out, is why doesn't the outer loop work?
The user needs to press '1' to continue, and any other key the program exits.
However, it still doesn't continue if the user presses '1' and instead exits anyway.
I tried adding a cin.clear() before cin >> repeat, but that doesn't work.
I also tried playing around with cin.ignore(), but that didn't seem to help either.
Any ideas?
Thanks
int main()
{
int repeat = '1';
stack<char> cstr;
char c;
while (repeat == '1')
{
cout << "Enter in a name: ";
while (cin.get(c) && c != '\n')
{
cstr.push(c);
}
cout << "\n Enter another name? 1 = Continue, any other key to exit the program";
cin >> repeat;
repeat = getchar();
}
}
There is nothing at all wrong with your code. It seems to be working fine for me.
EDIT: Sorry it doesn't work until you remove the getchar. Forgot to mention that. Simple way of finding out the error is to just display the value of the variable repeat to see what the value is and where it is going wrong.
Screenshot to show you that your codes work
Everything seems to be working fine. I would like to comment on your program structure though. For small programs like this it's ok but always best to practice the logical way. For questions like this you should implement the do while loop instead of the while loop so that it goes in without checking and then accepts the user input and checks with the post condition. Example below.
char repeat;
do
{
//Your codes in here
}while (repeat == '1');
It is more logical to use this method instead unless your question specifies you to use while loop. Anyhow hope this helps.
Run this . it will solve your problem somehow repeat=getchar was making repeat=10.
int main()
{
char repeat = '1';
stack<char> cstr;
char c;
while (repeat == '1')
{
cout << "Enter in a name: ";
cin.ignore();
while (cin.get(c) && c != '\n')
{
cstr.push(c);
}
cout << "\nEnter another name ? \nPress 1 to Continue : ";
cin >> repeat;
cout << endl;
}
system("pause");
}
The line cin >> repeat is tring to read an integer from the keyboard because repeat is a variable of type int. However, you are verifying if the integer read from the keyboard is equal to 49 (the ASCII code for the character '1'), which is not what you want. A solution would be to replace the line
int repeat = '1';
with
int repeat = 1;
and also replace
while (repeat == '1')
with
while (repeat == 1)
because then you are comparing the integer read from the keyboard with the integer 1 (rather than the character '1'). Also, at the end of the loop you read input from the keyboard and store it in repeat but then you immediately read input again and store that value in repeat, replacing its previous value. To solve this, replace the line
repeat = getchar();
with
getchar();
and that should do it.
cin >> repeat;
it reads repeat as int. (1 is not equal '1')
repeat = getchar();
It reads int code of special char '\n' - symbol end of line.
You must use
char repeat = '1';
Or write
int repeat = 1;
and not use getchar()

Can you stop letters being entered for an integer?

I was wondering if there was anyways of stopping letters being entered for an integer. Here is the code which I have been using in my int main.
do
{
cout << "Player 1 please enter the value of the row you would like to take ";
cin >> row;
}while (row != 0 && row != 1 && row != 2 && row != 3);
My problem with this code is that if the user enters a letter it creates a never ending loop. Any help would be much appreciated.
Standard library doesn't provide anything that would filter characters that are entered through standard input. I believe you could use libraries like curses to do that.
What you can do, though, is check whether input suceeded. operator>> for int will set the stream's state to failbit if it couldn't extract an integer (for example, when it encountered an 'a' or something like that. You can use extraction operators in boolean context, something like this:
cout << "Player 1 please enter the value of the row you would like to take ";
while (!(cin >> row) || (row < 0 || row > 3)) {
cout << "Invalid input, try again!\n";
// clear the error flags and discard the contents,
// so we can try again
cin.clear();
cin.ignore(std:numeric_limits<std::streamsize>::max(), '\n');
}
Note that if you enter for example 1abc, the read will succesfuly read 1 and leave the abc in the stream. This might not be a desired behaviour. If you wish to treat that as an error you can say
if ((cin >> std::ws).peek() != EOF) { /* there's more input waiting */ }
and act accordingly, or just unconditionaly ignore everything from the stream once you've got a value.
Get characters one at a time and only add the number characters to the string. Use
cin.get();
in a loop.

Why does my C++ program print an extra newline?

ok i have been at this for hours....
//after a character is entered, library routines are used to uppercase the
letters. loops the program until "1" is entered
char letter;
while (letter != '1')
{
cout << "Enter a letter: ";
cin.get(letter);
cout << char(toupper(letter)) << '\n';
}
everything works but it couts "Enter a letter: " twice...
here is a sample output
Enter a letter: h
H
Enter a letter:
Enter a letter: k
K
Enter a letter:
Enter a letter: a
A
i want it to look like this
Enter a letter: h
H
Enter a letter: k
K
Enter a letter: a
A
Can you help and explain why it is doing this....
When you enter your data, you type the letter then press ENTER. This adds your letter as well as the return character (\n) to the stream. Since cin.get() isn't going to wait for your input when there are still characters to extract from the stream, it's picking up the \n every other pass.
You can quickly fix this by adding cin.ignore:
while (letter != '1')
{
cout << "Enter a letter: ";
cin.get(letter);
cin.ignore(256, '\n');
cout << char(toupper(letter)) << '\n';
}
An alterative would be to use the >> operator as cin.get only retrieves one char at a time:
while (letter != '1')
{
cout << "Enter a letter: ";
cin >> letter;
cout << char(toupper(letter)) << '\n';
}
Just change the cin.get(letter) to cin >> letter;, and it will work as expected.
EDIT: Thought I give some more information on this. get() extracts exactly one character from the stream, which will leave the newline character in there as others have pointed out. The next call to get() will extract it and terminate immediately instead of waiting for input, since the stream still had data. The >>-operator on the other hand, is made exactly for what you're trying to do here: Read a value from stdin until the return key is pressed. So it consumes the newline as well, causing the next call to operator<<() to block until new data is entered by the user.
Note: One more thing to keep in mind: >>-extracting into a char will extract at most one character from the stream, but it does not prevent the user from entering more characters before pressing enter. This will produce some output like the following:
niko#lethal-guitar:~$ ./a.out
Enter a letter: a
A
Enter a letter: asas
A
Enter a letter: S
Enter a letter: A
Enter a letter: S
This is because the operator removes one char and the newline, but keeps the remaining chars in the stream. These will terminate the next three operator>>()-calls immediately.
For starters, because you don't check whether cin.get succeeds
or not. You will almost certainly output the last character you
read twice. Your loop should be:
while ( letter != '1' && cin.get( letter ) ) ...
or
while ( cin.get( letter ) && letter != '1' ) ...
Note too that on most systems, cin.get() will not return until
you hit enter (supposing input from the keyboard). So you'll
output "Enter a letter: ", and then wait until the enter key
is pressed. You'll then loop without waiting, reading all of
the characters you've entered, until you've read '\n'. There
are no provisions for character-wise input in the C++ standard,
and the techiques for doing it vary radically from one system
to the next.