c语言入门(九)--数组读取字符串

1. 字符数组初始化传递

字符数组的定义方法与上一节的一维数组类型相似

#include <stdio.h>

void main(){
    char c[10];
}

字符数组初始化 

​#include <stdio.h>

void main(){
    // char c[5]={'h','e','l','l','o'};  // 不建议这么写
    char c[5]="hello";

    printf("%s\n", c); // 会打印乱码
}

​

报错原因:因为printf通过%s打印字符串是会一次输出每一个字符,当到结束符'\0'时结束

2. scanf读取字符串

错误写法:

#include <stdio.h>

void main(){
    char c[11];
    scanf("%s",c);  // 假设输入 hello world
    printf("%s\n",c);  // 只会输出 hello
}

原因:scanf通过"%s"读取字符串时,会忽略【空格】和【回车】

正确写法:

#include <stdio.h>

void main(){
    char c[10];
    char d[10];
    scanf("%s%s",c,d);  // 假设输入 hello world
    printf("%s %s\n",c,d);  // 只会输出 hello
}

3. gets函数和puts函数

gets函数:

类似于scanf函数,用于读取标准输入,

特点:

· 可以一次读一行字符串

· 自动输入一个"\0"结数符

· 与scanf的区别是scanf遇到【空格】后不存储,gets遇到【回车\n】不存储

#include <stdio.h>

void main(){
    char c[20];
    // gets函数中放入字符数组的数组名
    gets(c); // 假设输入 hello world
    // puts函数中放入字符数组的数组名
    puts(c); // 输出 hello world
}

puts函数:

类似于printf函数,用于标准输出,

特点:

· 只能输出字符

· 多输入一个换行符等价于printf("%s\n")

4. str系列字符串造作函数

#include <stdio.h>
#include <string.h>
void main(){
    int len;
    char c[20];
    char d[100]="world";
    gets(c);  // 假设输入 hello
    puts(c);  // 输出 hello
    len = strlen(c); // 获取c的长度
    printf("len=%d\n",len); // 输出 len=5
    // 把 d 拼接到 c中
    strcat(c,d);
    puts(c); // 输出 helloworld
    char e[100];
    // 把 c 复制给 e;
    strcpy(e,c);
    puts(e); // helloworld
    // 比较字符串大小
    printf("c?e=%d\n", strcmp(c,e)); // 相等时是 0;
    printf("c?d=%d\n", strcmp(c,d)); // 小于时是负值;
    printf("d?c=%d\n", strcmp(d,c)); // 大于时是正值;
}

  • 6
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Y_努力_strive

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值