fgets() does not work as I expect it to

后端 未结 3 1609
逝去的感伤
逝去的感伤 2021-01-19 17:17

Can anyone tell me why this code does not work? When i run, it just prints out \"Enter info about trail 1\" and without any input, skips to another step.

#in         


        
相关标签:
3条回答
  • 2021-01-19 17:43

    The perl language gives you chomp, which removes the newline from lines read from input. I find it a useful function to have lying around,

    char*
    chomp(char* p)
    {
        if(!p) return p;
        size_t len=strlen(p);
        //if(len<=0) return(p);
        if(len>0) len--;
        if(p[len]=='\n') p[len--]='\0';
        if(len>=0) if(p[len]=='\r') p[len--]='\0';
        return(p);
    }
    

    So, declare a variable to use to read a line, and then just use gets to parse the line. Loads clearer. And notice that your array is an array of MAX arrays of char[20], and you may well enter a far larger line. It can be effective to read the entire line entered, and then extract the part you want,

    char array[MAX][20];
    int ndx;
    char line[100];
    for( ndx=0; fgets(line,sizeof(line)-1),stdin); ++ndx ) {
        chomp(line);
        strncpy(array[ndx],line,sizeof(array[ndx])-1);
        //combine both into one line:
        //strncpy(array[ndx],chomp(line),sizeof(array[ndx])-1);
        /*NULL termination of array[ndx] left as exercise for reader*/
    }
    
    0 讨论(0)
  • 2021-01-19 17:58

    Issue

    The scanf function in main reads the integer, but leaves the newline \n on the input stream. When the first loop iteration of readingArrays comes around, fgets sees this newline and assumes you have already entered your trail info and pressed enter. It prints the empty string and newline, and goes on to the next iteration.

    Solution

    One solution would be to tell scanf to read and ignore whitespace after the digit by adding a space after %d format specifier.

    So to get numberOfTrails from stdin, you would do

    scanf("%d ",&numberOfTrails);
    

    Thanks to @Ray for pointing out this solution!

    0 讨论(0)
  • 2021-01-19 18:02

    1) Add this line after scanf() : getchar()

    2) Change fgets (...) 4 to 19.

    The program will work.

    0 讨论(0)
提交回复
热议问题