fgets的原型是char* fgets(char* s, int n, FILE* fp);
参数数量比较多,有3个。而fgets相比于gets有一个显著的差异就是fgets会将行末的换行符算到读入的字符串里面。因此相同且正常(输入无错误,缓冲区够大)的状况下,fgets读入的字符串会比gets在末尾'\0'前面多一个换行符;行长度超出缓冲区大小时只读入前 n-1 个字符。所以,gets(s);至关于html
fgets(s, sizeof(s), stdin);
if(s[strlen(s) - 1] == '\n') s[strlen(s) - 1] = '\0'; // 去掉换行符数组
其实,末尾这个换行符是另有妙用的。this
#include <stdio.h> #include<string.h> int main() { int a,b=0,c=0; char line[100],newline[100]; char temp; scanf("%d%c",&a,&temp); while(a--) { fgets(line,sizeof(line), stdin);//if scanf("%s",line); then whitespace can not inputed. //printf("%d\n",strlen(line)); memset(newline,'\0',sizeof(newline));//temporary newline int i,j; i=0;j=0; int isMoreSpace=0; for(;i<strlen(line);i++) { if(line[i]==' ') isMoreSpace++; else { if(isMoreSpace>0) { newline[j++]=' '; } newline[j++]=line[i]; isMoreSpace=0; } } printf("%s\n",newline); } return 0; } /*input 3 hello kugou ni hao a ni ni ni ni */
设置两个变量,分别记录当前输入的字符和上一次输入的字符,“上一个字符”初始化为EOF。若是当前输入字符为空,上一个输入字符也为空,则忽略当前输入的字符。spa
#include <stdio.h> /* http://www.cnblogs.com/wuzhenbo/archive/2012/12/02/2798029.html 当前输入字符能够分为两种状况: 一、当前输入字符不为空,则直接输出这个字符便可; 二、当前输入字符为空,这种状况又能够分为两种状况: ①、上一个输入字符也为空,则忽略这次输入的空格便可; ②、上一个输入字符不为空,则直接输出这个字符便可。 基本思想是: 设置两个变量,分别记录当前输入的字符和上一次输入的字符,“上一个字符”初始化为EOF。 若是当前输入字符为空,上一个输入字符也为空,则忽略当前输入的字符。 */ int main() { int c, pc; /* c = character, pr = previous character */ /* set pc to a value that wouldn't match any character, in case this program is over modified to get rid of multiples of other characters */ pc = EOF; int a; char tmp; scanf("%d%c",&a,&tmp); while ((a>0)&&(c = getchar()) != EOF) { if (c == ' ') if (pc != c) /* or if (pc != ' ') */ putchar(c); /* We haven't met 'else' yet, so we have to be a little clumey */ if (c != ' ') { if(c=='\n') a--; putchar(c); } pc = c; } return 0; } /*input 3 hello kugou ni hao a ni ni ni ni */