views:

330

answers:

5

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?

+2  A: 

Use the function getchar()

Maurizio Reginelli
gets a single character, not a line. Perrhaos you meant gets() but that is a dangerous function and fgets() should be used instead.
Clifford
@Clifford, the OP did show an example of the user pressing a single key (e.g [enter]) ...
Tim Post
Ah! I was addressing the requirement to implement Console.ReadLine() functionality. I see your point now.
Clifford
A: 

Take a look here: Console..::.ReadLine Method

Leniel Macaferi
Not that I know anything about .Net, but does this have a c interface?
dmckee
Microsoft has Visual C++. If you want to test it take a look at the Express version (free): http://www.microsoft.com/express/Downloads/#2008-Visual-CPP
Leniel Macaferi
A: 

try this:

printf ("Press Enter to continue"); 
scanf(“%[^\n]“,str);
Hortinstein
+2  A: 

You could use fgets(), like so:

#include <stdio.h>

fgets(buf, sizeof(buf), stdin);
S.C. Madsen
A: 

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
dmckee
What you said is true of gets() rather than getchar() which gets just a single character from stdin. Note that getline() is a GNU extension to the standard library. C++ has a similar istream::getline() and ::getline() functions not to be confused. In ISO C, use fgets().
Clifford
@Clifford: `getchar` will respond on *any* character, not just enter. Now, that may be the OP's intention, and it *will* work, but it is not what he asked for. But my problem with it is that it is a little fragile if the user is not paying attention (i.e. they forget the prompt is coming and start typing the next command, `getchar` eats that first character immediately so the terminal doesn't pause, and their next input is short the leading character). And yes, `fgets` is c standard, but these days `getline` is part of POSIX and not just a GNU thing anymore.
dmckee
Ah! I was addressing the requirement to implement Console.ReadLine() functionality. I see your point now. Although getchar() is not subject to buffer overflows, and where stdin is line buffered, will not return until ENTER is pressed.
Clifford
Regarding getline() being POSIX; true, but not Win32. It is not clear from the tags that this is to be implemented on POSIX. I've no objection to its use, but just wanted to be clear on portability.
Clifford
@Clifford: Fair enough. I live in a POSIX world, which colors my thinking.
dmckee