Loading your workspace…
Loading your workspace…
Read a line of text and find its length by counting characters, without calling strlen.
#include <stdio.h>
int main(void) {
char text[200];
int length = 0;
printf("Enter a string:\n");
if (fgets(text, sizeof text, stdin) == NULL) {
printf("Error: no input\n");
return 1;
}
while (text[length] != '\n' && text[length] != '\0') {
length++;
}
printf("Length: %d\n", length);
return 0;
}
Input
Hello WorldOutput
Enter a string:
Length: 11Input
(no input)Output
Enter a string:
Length: 0The length is the number of characters before the terminator. The newline that fgets keeps is not part of the text, so the loop stops at it as well.
Spaces are counted, because they are characters of the string. Only the newline and the terminator end the count.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
Hello World
Expected output
Enter a string: Length: 11
Expected output
Enter a string: Length: 0
11; the space counts as a character.
fgets keeps the newline at the end of the line, which is not part of the string's text.
No. strlen counts characters before the '\0', so the terminator is excluded.
Any line up to 199 characters plus the terminator, since the buffer holds 200 bytes.
O(n) in the length of the string.
Back to all RCU 21BCA1C1P lab programs.