S1E19动动手写strcmp函数
#include<stdio.h>int main()
{
char str1,str2;
printf("Please input the first string:");
scanf("%s",&str1);
printf("Please input the second string:");
scanf("%s",&str2);
signed int i;
printf("Please input the number you'd like to compare:");
scanf("%d",&i);
if (str1==str2)
{
printf("The result is 0!\n");
}
else
{
printf("The result is %d\n",str1-str2);
}
return 0;
}
如果输入的字符串中间有空格就出错,为什么? 本帖最后由 一点点儿 于 2022-8-9 15:44 编辑
scanf扫描到空格时,就认为对str的赋值结束,并忽略了后面的字符串。注意:后面的字符串依然还在stdin缓冲区。
怎么才能解决这样的问题呢?
可以用gets()代替scanf():scanf("%s",&str1)改为gets(str1)
scanf("%s",&str2)改为gets(str2)
如下:
#include <stdio.h>
int main() {
char str1, str2;
printf("Please input the first string:");
gets(str1);
printf("Please input the second string:");
gets(str2);
signed int i;
printf("Please input the number you'd like to compare:");
scanf("%d", &i);
if (str1 == str2) {
printf("The result is 0!\n");
} else {
printf("The result is %d\n", str1 - str2);
}
return 0;
} #include <stdio.h>
int main() {
char str1, str2;
printf("Please input the first string:");
gets(str1);
printf("Please input the second string:");
gets(str2);
signed int i;
printf("Please input the number you'd like to compare:");
scanf("%d", &i);
if (str1 == str2) {
printf("The result is 0!\n");
} else {
printf("The result is %d\n", str1 - str2);
}
return 0;
}
这样 一点点儿 发表于 2022-8-8 19:07
这样
作为 C 语言里少见的被直接删除的函数,个人认为 gets 还是能不用就不用。可以使用 fgets 之类的函数进行代替。
(偏题 这个代码的功能好像和我认识的 strcmp 不太一样...) 一点点儿 发表于 2022-8-8 19:07
这样
谢谢,还有一个问题,最后得出的结果是用两个字符的什么相减?去查了ASCII字符表发现得出的结果与字符对应的十进制数并不相等
zyxmm 发表于 2022-8-9 16:46
谢谢,还有一个问题,最后得出的结果是用两个字符的什么相减?去查了ASCII字符表发现得出的结果与字符对 ...
最后得出的结果是用两个字符对应的ASCII码十进制数相减
我运行得出的结果没错,
str[]是从0开始索引的,
你会不会是按照str[]从1开始索引验证结果的?{:9_241:} 一点点儿 发表于 2022-8-9 17:03
最后得出的结果是用两个字符对应的ASCII码十进制数相减
我运行得出的结果没错,
str[]是从0开始索引的 ...
对,我从1开始索引的,按0开始结果就对了,谢谢
页:
[1]