Question

I need to accomplish the same behavior as .NET Console.ReadLine function provides. The program execution should continue when the user pushes enter key.

The following code is not sufficient, as it requires additional input:

printf ("Press Enter to continue");
scanf ("%s",str); 

Any suggestions?

Was it helpful?

Solution

You could use fgets(), like so:

#include <stdio.h>

fgets(buf, sizeof(buf), stdin);

OTHER TIPS

Use the function getchar()

try this:

printf ("Press Enter to continue"); 
scanf(“%[^\n]“,str);

getline is probably better than getchar in most cases. It allows you to capture all of the user's input before the "enter" and is not subject to buffer overflows.

char *buf=NULL;
printf("Press enter to continue: ");
getline(&buf,0,stdin);
// Use the input if you want to
free(buf); // Throw away the input

You can use do while with scanf function.

do{
    scanf("%s",str1);
}while(str1[0] == '\0' || str1[0] == '\r' || str1[0] == '\n');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top