1

I want to calculate the length of an char array in C with a while loop. But If I insert otto it returns the length of 5. Shouldn't be 4 the right answer?

char eingabe[255];

printf("geben Sie eine Zeile ein:");
fgets(eingabe, 255, stdin);

int i = 0;
while (eingabe[i] != '\0')
{
    ++i;
}

printf("Laenge: %d\n", i);
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
torhoehn
  • 95
  • 17

4 Answers4

8

It's very likely that eingabe contains:

{ 'o', 't', 't', 'o', '\n', '\0', junk ... }
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
7

Check the man page of fgets().

Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.

As you are reading from stdin, it stores the trailing newline [\n] character also in the supplied buffer.

Change your check to while ((eingabe[i] != '\0') && (eingabe[i] != '\n')). Hope this will solve your issue.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

A newline character '\n' makes fgets stop reading, but it is considered a valid character by the function, and included in the string copied to the result. If you would like to avoid this, use fscanf like this:

fscanf(stdin, "%254[^\n]", eingabe);

Note the limit in the format: it is less than the actual length of the buffer to accommodate the null terminator.

Note: You can use strlen to compute the length of the string. It does the same thing as your for loop:

int i = strlen(eingabe);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

The size of eingabe is 255. Now, if you want the number of initialized characters in it you should use strlen. But first, insert this code:

int n;
for(n = 0; n < 255; n++){
  if(eingabe[n] == '\n'){
    eingabe[n] = '\0';
  }
}
eingabe[254] = '\0';

This code replaces the '\n' character with a NULL character. Without this, strlen will return wrong values. I also include eingabe[254] = '\0'; so that if the string read in is long enough that the newline character does not fit in the buffer, there is still a NULL character so that strlen can function properly

Gophyr
  • 406
  • 2
  • 11