简体   繁体   中英

fgets() does not work as I expect it to

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.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 15

void readingArrays(int numberOfTrails,char arr[MAX][20]);

char array[MAX][20];

int main(void)
{
    int numberOfTrails;
    printf("Enter the number of trails\n");
    scanf("%d",&numberOfTrails);

    readingArrays(numberOfTrails,array);

    return 0;
}

void readingArrays(int numberOfTrails,char arr[numberOfTrails][20])
{
    for(int i=0;i<numberOfTrails;i++)
    {
        printf("Enter info about trails %d\n",i+1);
        fgets(arr[i],4,stdin);
        //getchar();
        //strtok(arr[i], "\n");
        printf("%s\n",arr[i]);
    }
}

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!

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*/
}

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

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

The program will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM