fgets() does not work as I expect it to

后端 未结 3 1608
逝去的感伤
逝去的感伤 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*/
    }
    

提交回复
热议问题