fgets will read a carriage return. Sometimes we do not expect there is a line break in the string.
#include <stdio.h>
int main (int argc,char *argv[])
{
char str[30]="";
//scanf("%s",str);
printf("随便输入一个字符串呗:");
fgets(str,sizeof(str),stdin);
printf("%s",str);//注意:此处并没有换行符
printf("咋就换行了呢?\n");
return 0;
}
operation result
Wrap reasons: the input string, with newline characters input character string, this time fgets () preserved the line breaks, and output. In many cases this will cause trouble. That as to get rid of it
Solution
1, cut from the string '\ n' at
strtok(str,"\n");//切割函数,从 \n 切割
#include <stdio.h>
int main (int argc,char *argv[])
{
char str[30]="";
//scanf("%s",str);
printf("随便输入一个字符串呗:");
fgets(str,sizeof(str),stdin);
strtok(str,"\n");
printf("%s",str);
printf("咋就换行了呢?\n");
return 0;
}
The results:
2, to obtain a last location string is zero true length
str[strlen(str)-1]='\0';
#include <stdio.h>
#include <string.h>
int main (int argc,char *argv[])
{
char str[30]="";
//scanf("%s",str);
printf("随便输入一个字符串呗:");
fgets(str,sizeof(str),stdin);
str[strlen(str)-1]='\0';
printf("%s",str);
printf("咋就换行了呢?\n");
return 0;
}
operation result: