您的位置:首页 > 编程语言 > C语言/C++

【C语言】编写一个将输入复制到输出的程序,并将其中连续的多个空格用一个空格代替

2016-04-09 11:22 731 查看


数组

memset清空数组

fgets替代gets

fgets的原型是
char* fgets(char* s, int n, FILE* fp);
参数数量比较多,有3个。而fgets相比于gets有一个显著的差别就是fgets会将行末的换行符算到读入的字符串里面。所以相同且正常(输入无错误,缓冲区够大)的情况下,fgets读入的字符串会比gets在末尾'\0'前面多一个换行符;行长度超出缓冲区大小时只读入前 n-1 个字符。因此,gets(s);相当于

fgets(s, sizeof(s), stdin);

if(s[strlen(s) - 1] == '\n') s[strlen(s) - 1] = '\0'; // 去掉换行符

其实,末尾这个换行符是另有妙用的。

#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
*/


getchar

设置两个变量,分别记录当前输入的字符和上一次输入的字符,“上一个字符”初始化为EOF。如果当前输入字符为空,上一个输入字符也为空,则忽略当前输入的字符。

#include <stdio.h>
/* http://www.cnblogs.com/wuzhenbo/archive/2012/12/02/2798029.html 当前输入字符可以分为两种情况:

  1、当前输入字符不为空,则直接输出这个字符即可;

  2、当前输入字符为空,这种情况又可以分为两种情况:

  ①、上一个输入字符也为空,则忽略此次输入的空格即可;

  ②、上一个输入字符不为空,则直接输出这个字符即可。

基本思想是:
  设置两个变量,分别记录当前输入的字符和上一次输入的字符,“上一个字符”初始化为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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: