C - equivalent of .NET Console.ReadLine
I need to accomplish the same behavior as .NET Conso开发者_如何学Cle.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?
You could use fgets(), like so:
#include <stdio.h>
fgets(buf, sizeof(buf), stdin);
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');
精彩评论