Check if user input into an array is too long?

前端 未结 6 2113
执笔经年
执笔经年 2021-01-24 18:19

I am getting the user to input 4 numbers. They can be input: 1 2 3 4 or 1234 or 1 2 34 , etc. I am currently using

int array[4];
scanf(\"%1x%1x%1x%1x\", &ar         


        
6条回答
  •  情歌与酒
    2021-01-24 19:01

    Your question might be operating system specific. I am assuming it could be Linux.

    You could first read an entire line with getline(3) (or readline(3), or even fgets(3) if you accept to set an upper limit to your input line size) then parse that line (e.g. with sscanf(3) and use the %n format specifier). Don't forget to test the result of sscanf (the number of read items).

    So perhaps something like

    int a=0,b=0,c=0,d=0;
    char* line=NULL;
    size_t linesize=0;
    int lastpos= -1;
    ssize_t linelen=getline(&line,&linesize,stdin);
    if (linelen<0) { perror("getline"); exit(EXIT_FAILURE); };
    int nbscanned=sscanf(line," %1d%1d%1d%1d %n", &a,&b,&c,&d,&lastpos);
    if (nbscanned>=4 && lastpos==linelen) {
      // be happy
      do_something_with(a,b,c,d);
    }
    else {
      // be unhappy
      fprintf(stderr, "wrong input line %s\n", line);
      exit(EXIT_FAILURE);
    }
    free(line); line=NULL;
    

    And once you have the entire line, you could parse it by other means like successive calls of strtol(3).

    Then, the issue is what happens if the stdin has more than one line. I cannot guess what you want in that case. Maybe feof(3) is relevant.

    I believe that my solution might not be Linux specific, but I don't know. It probably should work on Posix 2008 compliant operating systems.

    Be careful about the result of sscanf when having a %n conversion specification. The man page tells that standards might be contradictory on that corner case.

    If your operating system is not Posix compliant (e.g. Windows) then you should find another way. If you accept to limit line size to e.g. 128 you might code

    char line[128];
    memset (line, 0, sizeof(line));
    fgets(line, sizeof(line), stdin);
    ssize_t linelen = strlen(line);
    

    then you do append the sscanf and following code from the previous (i.e. first) code chunk (but without the last line calling free(line)).

提交回复
热议问题