Re: Getting user input in Linux?
- From: John Bode <john_bode@xxxxxxxxxxx>
- Date: Thu, 31 Jan 2008 12:14:28 -0800 (PST)
On Jan 30, 10:17 pm, Zach <net...@xxxxxxxxx> wrote:
Hi,
I run Linux 2.6.18 and am seeking a way in C to get user input. I want
them to have the chance to enter a value and have it assigned to a
variable.
I currently have:
int* s1;
printf("Enter first integer: %d\n",s1);
scanf(&s1);
When I run this it automatically enters 0. It never pauses and thus
does not allow me to type in a value.
Zach
2 questions:
1. Are you *sure* this is the code you wrote?
2. Did you #include <stdio.h>?
I ask because the compiler should yak on the scanf() line as written.
scanf() expects the first parameter to be of type const char *, not
int**.
Here's a minimal example of how that code should be written:
#include <stdio.h>
int main(void)
{
int s1;
printf("Enter the first integer: ");
fflush(stdout);
if (scanf("%d", &s1) < 1)
{
printf("Input value was not an integer\n");
}
else
{
printf("You entered %d\n", s1);
}
return EXIT_SUCCESS;
}
scanf() isn't the best tool for interactive user input; it doesn't
handle errors all that well, and can leave garbage in the input stream
that can cause future scanf() calls to fail. I personally prefer
using fgets() to read everything in as a string, and then covert using
tools like strtol() or strtod(). It gives you more flexibility in
dealing with bad input and reduces the likelihood of buffer overruns.
.
- References:
- Getting user input in Linux?
- From: Zach
- Getting user input in Linux?
- Prev by Date: Re: How Do You Pronounce char?
- Next by Date: Re: translating oo features to C
- Previous by thread: Re: Getting user input in Linux?
- Next by thread: declaration of variable in for loop
- Index(es):
Relevant Pages
|