Home > other >  Fgets function in for loop overwrittes old input
Fgets function in for loop overwrittes old input

Time:09-27

I'am trying to write Names into a char array. I'am using fgets for this. My problem is that my code overwrittes the old input each time their is a new one.

I'am using the compare for NULL because I want to end the input sequency with pressing CTRL D.

char input[MAX];

for(;;) {
    printf("Input:\n");
    if (fgets(input, MAX, file) == NULL){
        printf("EOF\n");
        break;
    }
}
printf("%s", input);

CodePudding user response:

Edited for portability. (replaced VLA with fixed length array.)

"I don't understand why I need a 2 Dimension Array"

char input[MAX];

creates space for a single char array with space for MAX-1 characters, leaving one byte for the terminating null character, \0.

"Anna", "Peter" and "Leonie" are each null terminated char arrays, each defining a C string. If they are to be stored in an array, the array needs to be created with space for each of them, and each space needs its own starting location provided by the value of the first index in the declaration:

   char input[NUM_STRINGS][MAX];

The second index provides the space. Now each string has its own space, as shown here:

input[0]//each of following can contain up to MAX-1 characters
input[1]
input[3]
...
input[num_strings]

This example implements what my comments under your question were trying to explain...

#define MAX 100
#NUM_STRINGS 10

int main(int argc, char *argv[])
{
    char input[NUM_STRINGS][MAX] = {0};//zeroed to initialize    
    for(int i = 0;i < NUM_STRINGS; i  )
    {
        printf("Input:\n");
        if (fgets(input[i], MAX, stdin) == NULL)
        {
            printf("EOF\n");
            break;
        }
        //remove newline
        input[i][strcspn(input[i], "\n")] = 0;
        printf("%s", input[i]);
    }
    return 0;
}

Note, although you can use ctrl-d, you do not need to. The loop will exit when num_strings is reached.

  •  Tags:  
  • c
  • Related