C语言如何输入输出一个字符串 您所在的位置:网站首页 输出字符串的每一个字符 C语言如何输入输出一个字符串

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

2023-10-07 19:08| 来源: 网络整理| 查看: 265

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

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

一 scanf&&printf

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

#include 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 int main(){ char s[10]; scanf("%s",s); //or scanf("%s") printf("%s",s); return 0; }

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

二 字符串处理函数

I. 逐个字符的处理

#include #include 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 #include int main(){ char s[10]; gets(s); puts(s); return 0; }

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



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有