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;
}

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

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐