c, and strlen fgets

fgets function reads from the file '\ n' and stored in the '\ n' and then to add a '\ 0' string configuration.

However fgets function to specify the number of characters read, if the specified n, only a maximum of n-1 read. fgets reading of the n-1 characters, read '\ n' or met all end when one reads EOF three cases.

Verification code is as follows:

#include <stdio.h>
#include <string.h>
#define MAXLENGTH 101
int main(){

char str[MAXLENGTH];
fgets(str, MAXLENGTH, stdin);
int length = strlen(str);
int str_length = strlen(str);
int num = 0;
printf("%d\n",str_length);
printf("%s",str);

for (int i=0; i<= length; i++){
if (str[i] ==' '){
num++;
str_length--;
printf("num=%d\n",num);
}
if (str[i] == '\0'){
printf("0000,i=%d\n",i);
}
if (str[i] == '\n'){
printf("nnnn,i=%d\n",i);
}
}
num++;
printf("num = %d \n",num);
//printf("%2f",(float)(str_length)/num);

return 0;
}

result:

 

Guess you like

Origin www.cnblogs.com/fanru5161/p/11547142.html