Wait Until User Presses Enter in C++

Press Any Key to Continue function in C

Use the C Standard Library function getchar() instead as getch() is not a standard function, being provided by Borland TURBO C for MS-DOS/Windows only.

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getchar();

Here, getchar() expects you to press the return key so the printf statement should be press ENTER to continue. Even if you press another key, you still need to press ENTER:

printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");
getchar();

If you are using Windows then you can use getch()

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
//if you press any character it will continue ,
//but this is not a standard c function.


char ch;
printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");
//here also if you press any other key will wait till pressing ENTER
scanf("%c",&ch); //works as getchar() but here extra variable is required.

Wait for press enter in C inside a while loop?

If this code (with additional fflush)

#include <stdio.h>
#include <stdlib.h>
int main()
{
int choice;
while(1){
printf("1.Create Train\n");
// print other options
printf("\nEnter Your choice : ");
fflush(stdin);
scanf("%d", &choice);
// do something with choice
// ...
// ask for ENTER key
printf("Press [Enter] key to continue.\n");
fflush(stdin); // option ONE to clean stdin
getchar(); // wait for ENTER
}
return 0;
}

does not work properly.

Try this code (with loop):

#include <stdio.h>
#include <stdlib.h>
int main()
{
int choice;
while(1){
printf("1.Create Train\n");
// print other options
printf("\nEnter Your choice : ");
fflush(stdin);
scanf("%d", &choice);
// do something with choice
// ...
// ask for ENTER key
printf("Press [Enter] key to continue.\n");
while(getchar()!='\n'); // option TWO to clean stdin
getchar(); // wait for ENTER
}
return 0;
}

How do I read in the Enter key as an input in C?

You can use the getc function in stdio.h to wait until a key is pressed. This C code will wait for the enter key to be pressed then output "Continued!":

#include <stdio.h>

int main(){
printf("Press any key to continue");
getc(stdin);
printf("Continued!");
return 0;
}

C++ wait for user input

Several ways to do so, here are some possible one-line approaches:


  1. Use getch() (need #include <conio.h>).

  2. Use getchar() (expected for Enter, need #include <iostream>).

  3. Use cin.get() (expected for Enter, need #include <iostream>).

  4. Use system("pause") (need #include <iostream>, Windows only).

    PS: This method will also print Press any key to continue . . . on the screen. (seems perfect choice for you :))


Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

Repeat until user presses enter

the following code is from kbhit for linux

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;

tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

ch = getchar();

tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);

if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}

return 0;
}

int main(void)
{
while(!kbhit())
puts("Press a key!");
printf("You pressed '%c'!\n", getchar());
return 0;
}

Continue iterating/repeating while loop until enter (or arbitrary key) is pressed

Here is example code that works using the select call.

It only works for newline because the kernel TTY layer will hold up until it gets a newline.

So, for any other char (e.g. space), we'd have to issue the ioctl calls I mentioned in my top comments to put the layer into "raw" mode (vs. the default of "cooked"). If you need that, see tcgetattr and tcsetattr calls.

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <sys/time.h>
#include <sys/select.h>

int
main(void)
{
int fd;
char buf[10];
int len;
fd_set rdset;

fd = 0;

while (1) {
// this is do whatever until newline is pressed ...
printf(".");
fflush(stdout);

// set up the select mask -- the list of file descriptors we want to
// wait on for read/input data available
FD_ZERO(&rdset);
FD_SET(fd,&rdset);

// set timeout of 1ms
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 1000;

// wait for action on stdin [or loop if timeout]
// the first arg must be: the highest fd number in the mask + 1
len = select(fd + 1,&rdset,NULL,NULL,&tv);
if (len <= 0)
continue;

// we're guaranteed at least one char of input here
len = read(fd,buf,1);
if (len <= 0)
continue;

// wait for newline -- stop program when we get it
if (buf[0] == '\n')
break;
}

printf("\n");

return 0;
}

getchar() doesnt wait for enter press

In the following line:

scanf ("%d",&options);

you actually enter a number, and a newline character. The scanf function reads only the number. It leaves the newline (\n) in the input stream.

When you call getchar(), it will find a newline in the input stream. Hence, it will read it without waiting for user input. It only wait for user input if it didn't find anything in the input stream.

A possible workaround for this is to call getchar two times instead of one.
The first call will read the already existing newline in the stream. The second call won't find anything in the input stream. So, it will wait for user input as you expect.


I have some small comments that aren't related to your question:

  • You use scanf ("%f",&*a);. Why not just scanf("%f", a); or scanf("%f", &A); ?
  • Why you even create a pointer a for the variable A ?
  • I don't think you really need the variable c as well.
  • You don't need the variable i in the loop as well.
  • At the beginning of the loop, you keep re-initializing enteredA and enteredB variables to zero. That way, the condition in case 3: will be always true. You need to move these variables outside of the loop.
  • Your code also missing a #include <stdio.h>.
    I'd simplify things like the following:
#include <stdio.h>
#include <stdlib.h>

int main()
{
int enteredA = 0, enteredB = 0;
while (1)
{
int options;
float A, B;
printf ("Calculator\nAvailable options:\n[1]Enter value for A\n[2]Enter value for B\n[3]Addition\n[9]Exit\n");
scanf("%d", &options);
getchar(); // The extra getchar to read the newline left in the stdin.
system ("clear");
switch (options)
{
case 1:
printf("Enter a value for A:");
scanf("%f", &A);
enteredA++;
break;
case 2:
printf("Enter a value for B:");
scanf ("%f", &B);
enteredB++;
break;
case 3:
if (enteredA ==0 || enteredB == 0)
{
printf("A and B are not initialized yet. Please enter a value in the menu.\nPress [Enter] to continue to the menu:\n");
}
else
{
printf("%f + %f = %f\n", A, B, A + B);
}
getchar();
break;
case 9:
printf("Calculator Shut Down");
return 0;
}
system("clear");
}
}


Related Topics



Leave a reply



Submit