Input treatment with scanf() return

Asked

Viewed 148 times

0

I’m trying to write an input treatment in my C code in the excerpt where the n values of an array and are read. If there is an error in reading (if the input is a char for example), assign 885444751 to the value at the error position and proceed to the next (hence the continue). However, at the first invalid value it exits and jumps to the next step of the program. Why it behaves like this?

#include<stdio.h>
#include <stdlib.h>
int main(){
  
 int n, *valores, *sequencia, i, ret;
    ret = scanf("%d",&n);
    if(ret!=1)
      printf("0\n");
    else{
        valores = (int *)malloc(n*sizeof(int));
        sequencia = (int *)malloc(60*sizeof(int));
        for (i = 0; i < n; i++){
            if(scanf("%d", &valores[i])!=1){
                valores[i]=885444751;
                continue;
                
                
            }
        }
        printf("Pulei direto\n");
    }
  return 0;
}

  • I believe you’re assuming that when he finds something other than a number he’ll skip this non-numerical thing, which is not true.

1 answer

1


The main problem is that the buffer gets dirty and has to clean it. scanf() is not very suitable for very simple data entry. More organized is so (although it could be improved):

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    int ret = scanf("%d", &n);
    int *valores;
    if (ret != 1) {
        printf("0\n");
        return 1;
    } else {
        valores = malloc(n * sizeof(int));
        for (int i = 0; i < n; i++) {
            if (scanf("%d", &valores[i]) != 1) valores[i] = 885444751;
            int c;
            while ((c = getchar()) != '\n' && c != EOF) {}
        }
    }
    for (int i = 0; i < n; i++) printf("%d\n", valores[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • What would be the most appropriate function? getchar()?

  • https://answall.com/q/42981/101

Browser other questions tagged

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