从键盘输入一个字符串,删除字符串中所有空格后输出。

C编程从键盘输入一个字符串,删除字符串中所有空格后输出。

#include<stdio.h>

#include<stdlib.h>

#include<ctype.h> //isalpha()函数的头文件

int main()

{

char *p = NULL;

p =(char *)malloc(100*sizeof(char));    //将malloc函数返回的void *指针强制转换为char *指针

printf("请输入字符串:\n");

gets(p);    //输入字符串

printf("\n删除了所有空格和标点符号的字符串\n");

while (*p)

{

if (isalpha(*p))

{

printf("%c", *p);

}

p++;

}

printf("\n");

return 0;

}

运行效果:

扩展资料:

1、isalpha()函数

作用:判断是否为字母

头文件:#include&lt;ctype.h&gt;

原型:int isalpha(int ch)

返回值:若为英文字母,返回非0(小写字母为2,大写字母为1)。若不是字母,返回0。

2、gets()函数

原型:gets(数组名)

作用:把输入的字符串传入给定的数组中

头文件:#include&lt;stdio.h&gt;

返回值:正常时返回字符串存放的数组的首地址(指针),错误或遇到EOF时返回NULL

3、while(*p)

解读:*p内容有值,也就是while(*p)等同于while(*p!='\0'),\0是字符串结束的标志,字符串结束之前都有值

4、printf("%c",*p)

等同于putchar(*p),putchar()函数作用是向终端输出一个字符

5、scanf()函数与gets()函数的区别

在于输入的字符串是否中间有空格,对于gets()函数,只有遇到'\n'时才停止输入,对于scanf()函数,出现'\n'或空格都停止输入。

温馨提示:内容为网友见解,仅供参考
第1个回答  2012-01-10
#include <stdio.h>

void main()
{
int i,n=0;
char str[80]={0},dest[80]={0};
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(str[i] != ' ')
{
dest[n]=str[i];
n++;
}
}
printf("%s",dest);
}

以测试,运行成功。
第2个回答  推荐于2016-06-30
#include <stdio.h>
#include <conio.h>

int main()
{
char a[100];
char s;
int i = 0;
while((s = getche()) != 13)
{
if(s != ' ')a[i++] = s;
}
a[i] = '\0';
printf("\n%s\n", a);

}本回答被提问者采纳
相似回答