Fgets () doesn't work as I expect it to

Can someone tell me why this code is not working? When I start, it simply prints out "Enter information about path 1" and without entering it, will skip 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]);
    }
}
+4
source share
3 answers

Question

The scanf function basically reads an integer, but leaves the input string \n. When the first iteration of the loop begins readingArrays, it fgetssees this new line and assumes that you have already entered trail information and pressed the enter key. It prints an empty line and a new line and proceeds to the next iteration.

Decision

scanf , % d.

, numberOfTrails stdin,

scanf("%d ",&numberOfTrails);

@Ray !

+2

perl chomp, , . , ,

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);
}

, , , . . , MAX char [20], . , ,

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

1) scanf():  GetChar()

2) fgets (...) 4 19.

.

0

Source: https://habr.com/ru/post/1616814/


All Articles