Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scanf to accept user input

Tags:

c

gcc 4.4.2

I was reading an article about scanf. I personally have never checked the return code of a scanf.

#include <stdio.h>

int main(void)
{
  char buf[64];
  if(1 == scanf("%63s", buf))
  {
    printf("Hello %s\n", buf);
  }
  else
  {
    fprintf(stderr, "Input error.\n");
  }
  return 0;
}

I am just wondering what other techniques experienced programmers do when they use scanf when they want to get user input? Or do they use another function or write their own?

Thanks for any suggestions,

EDIT =========

#include <stdio.h>

int main(void)
{
    char input_buf[64] = {0};
    char data[64] = {0};

    printf("Enter something: ");
    while( fgets(input_buf, sizeof(input_buf), stdin) == NULL )
    {
    /* parse the input entered */
    sscanf(input_buf, "%s", data);
    }

    printf("Input [ %s ]\n", data);

    return 0;
}

I think most programmers agree that scanf is bad, and most agree to use fgets and sscanf. However, I can use fgets to readin the input. However, if I don't know what the user will enter how do I know what to parse. For example, like if the user was to enter their address which would contain numbers and characters and in any order?

like image 226
ant2009 Avatar asked Jan 27 '10 03:01

ant2009


People also ask

How do I use scanf to input?

In order to input or output the string type, the X in the above syntax is changed with the %s format specifier. The Syntax for input and output for String is: Input: scanf("%s", stringVariable); Output: printf("%s", stringVariable);

Which symbol is used in scanf () to store a value into a variable?

The '%' character is used in the format string of the scanf() and print() -like functions from the standard header <stdio. h> , to indicate place holders for variable data of several kinds. For example, the format specifier "%d" is a place holder for a value having type int .

Can scanf take two inputs?

Inputting Multiple ValuesIf you have multiple format specifiers within the string argument of scanf, you can input multiple values.


1 Answers

Don't use scanf directly. It's surprisingly hard to use. It's better to read an entire line of input and to then parse it (possibly with sscanf).

Read this entry (and the entries it references) from the comp.lang.c FAQ: http://c-faq.com/stdio/scanfprobs.html

Edit: Okay, to address your additional question from your own edit: If you allow unstructured input, then you're going to have to attempt to parse the string in multiple ways until you find one that works. If you can't find a valid match, then you should reject the input and prompt the user again, probably explaining what format you want the input to be in.

For anything more complicated, you'd probably be better off using a regular expression library or even using dedicated lexer/parser toolkits (e.g. flex and bison).

like image 60
jamesdlin Avatar answered Sep 22 '22 13:09

jamesdlin