Operation of function scanf()

Asked

Viewed 144 times

-1

Can anyone explain to me how the function scanf() works? Not the basic, but how does the mechanism it has to return the number of arguments that were read. To whom does it return? Why does it return?

2 answers

0

I’m not going to explain much, I’m going to show you something that people have a lot of difficulty with C: keyboard reading.

The program below reads 2 whole numbers per line. The program will only accept exactly the typing of 2 numbers per line, in sequence (but with spaces between them). If you have things that are not numbers you will get an error, and if you have more than 2 fields you will get an error, even if the additional fields are numerical.

#include <stdio.h>

int main(void)
{
  int n_read, x, y;
  char buf[100], tmp[100];

  for (;;)
  {
    printf("*\n");
    printf("* digite 2 numeros inteiros: ");

    // le uma linha completa, sem interpretar os dados
    fgets(buf, sizeof buf, stdin);

    // faz a leitura, mas aproveitando a linha digitada
    n_read = sscanf(buf, "%d%d%s", &x, &y, tmp);
    printf("* foram lidos %d campos\n", n_read);

    if (n_read < 2)
    {
      printf("* erro na leitura, faltando numeros\n");
      continue;
    }

    if (n_read > 2)
    {
      printf("* erro, campos adicionais no restante da linha\n");
      continue;
    }

    printf("* ok, leitura bem sucedida, x=%d e y=%d\n", x, y);
  }
}

0


It returns the number of assignments made to facilitate error handling.

Imagine that you should read a date (format yyyy-mm-dd), a temperature value and, optionally, a rainfall value. For example

2019-01-01 24.3 0
2019-01-02 24.6
2019-01-03 #na
2019-01-04 25 1.1

With fgets(buf, sizeof buf, stdin); sscanf(buf, "%d-%d-%d%lf%lf", &y, &m, &d, &t, &p); the returned values will be

5 para a primeira linha: tudo ok
4 para a segunda linha; falta pluviosidade
3 para terceira linha; falta temperatura e pluviosidade
5 para quarta linha

Browser other questions tagged

You are not signed in. Login or sign up in order to post.