Re: Getting user input in Linux?



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.
.



Relevant Pages

  • Re: help! :(
    ... <partially broken code snipped> ... to handle user input using scanfcorrectly) and you _STOP_ posting ... > sales for January it's stuck in the loop??? ... looks exactly like that nothing gets read and on the next call of scanf() ...
    (comp.lang.c)
  • Re: scanf behaviour
    ... I have to use scanf() because of my task's constrains. ... int main ... The scanfin the while loop consumes all non-numerical input ... user input a number that's too large to be stored in an integer. ...
    (comp.lang.c)
  • Re: scanf behaviour
    ... int main ... The problem you're facing is that when scanf() doesn't find what ... The scanfin the while loop consumes all non-numerical input ... user input a number that's too large to be stored in an integer. ...
    (comp.lang.c)
  • Re: Refresher questions in C/C++
    ... I'm trying to do some very basic programmes at the moment to get back ... Depending on what that warning is, it may or may not be safe to ignore ... scanf is usually not what you actually want ... "Press Enter to continue" prompt and wait for user input ...
    (comp.lang.c)
  • Re: scanf in a for loop
    ... > Does the scanf command pause the loop until the user input is received? ... This means that scanf() is looking for the ...
    (comp.lang.c)