鱼C论坛

 找回密码
 立即注册
查看: 1055|回复: 2

[已解决]关于字符串比较时使用getchar()函数

[复制链接]
发表于 2020-2-18 13:19:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 129784626 于 2020-2-18 13:22 编辑

使用getchar函数从键盘获取字符并赋值给数组时会自动添加结束符'\0'吗?

while ((str1[i++] = getchar()) != '\n');
str1[i + 1] = '\0';//该句需要吗?

代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include <time.h>
#include<string.h>
{
char str1[1024];
char str2[1024];
int i = 0;
int s=0;
printf("请输入字符串str1\n");
while ((str1[i++] = getchar()) != '\n');
str1[i + 1] = '\0';
i = 0;
printf("请输入字符串str1\n");
while ((str2[i++] = getchar()) != '\n');
str2[i + 1] = '\0';  //需不需要手动添加结束符?如果注释掉该句最后输出str2时会出现乱码
i = 0;
while ((str1 != '\0') || (str2 != '\0'))
{
        if (str1-str2)
        {
                s = str1 - str2;
                break;
        }
         i++;
}
printf("a与b值相差%d", s);
printf("%d\n", strlen(str1));//此处如果键盘输入一个字符,该处会输出3,
printf("%d\n", strlen(str2));
system("pause");
return 0;
}

谢谢大佬了!!!!
最佳答案
2020-2-18 13:44:58
QQ截图20200218134428.png
你测试下不就知道,不加你看多严重
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-2-18 13:44:03 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-18 13:44:58 | 显示全部楼层    本楼为最佳答案   
QQ截图20200218134428.png
你测试下不就知道,不加你看多严重
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-13 13:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表