C语言如何输入输出一个字符串

C语言习题中,经常遇到字符串的输入输出,我们在这里简单总结一下字符串的输入输出方式。

C语言中用一般用数组来处理字符串,这里暂时讨论一维数组的输入输出,二维之后再加上。
定义:char 数组名[常量]
输入输出:我们可用scanf&&printf或者字符串处理函数来输入输出,处理逐个字符用%c,整个字符串用%s。

一 scanf&&printf

I. 逐个字符的处理
以’.'来表示字符串的结束。

#include<stdio.h> 
int main(){
  	char s[10],i=0;
  	scanf("%c",s);  
  	while(s[i]!='.'){
  	scanf("%c",&s[++i]);
  	}
  	i=0;
  	while(s[i]!='.'){
  	printf("%c",s[i++]);
  	}
  	printf("%c",s[i++]);
  	return 0;
}
```

优点:可以接受含有空格和回车的字符串。
II. 整个字符串的输入输出

#include<stdio.h>
int main(){
 	char s[10];
 	scanf("%s",s);  //or scanf("%s")
 	printf("%s",s);
 	return 0;
 }

优点:简洁方便;
缺点:不能接受含有空格的字符串。

二 字符串处理函数<stdio.h>

I. 逐个字符的处理

#include<stdio.h>
#include<string.h>
int main(){
 	char s[10];
 	int i=0;
 	s[i]=getchar();
 	while(s[i]!='.'){
  	s[++i]=getchar();
 	}
 	i=0;
 	while(s[i]!='.'){
  	putchar(s[i++]);
 	}
	putchar(s[i]);
	return 0;
}

优点:可以接受含有空格和回车的字符串。
II. 整个字符串的输入输出

#include<stdio.h>
#include<string.h>
int main(){
 	char s[10];
 	gets(s);
 	puts(s);
 	return 0;
}

优点:简洁方便,也可以接受含有其他特殊字符的输入输出,如空格,回车等。推荐使用

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值