SharpAffair
SharpAffair

Reputation: 5478

C - equivalent of .NET Console.ReadLine

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?

Upvotes: 3

Views: 9787

Answers (5)

You can use do while with scanf function.

do{
    scanf("%s",str1);
}while(str1[0] == '\0' || str1[0] == '\r' || str1[0] == '\n');

Upvotes: 0

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

Upvotes: 0

S.C. Madsen
S.C. Madsen

Reputation: 5246

You could use fgets(), like so:

#include <stdio.h>

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

Upvotes: 6

Hortinstein
Hortinstein

Reputation: 2697

try this:

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

Upvotes: 2

Maurizio Reginelli
Maurizio Reginelli

Reputation: 3212

Use the function getchar()

Upvotes: 2

Related Questions