c - 这个程序中的strcmp有什么问题?

标签 c strcmp

当我运行程序并回答"is"时,它告诉我我错了。有人知道执行此类程序的方法吗?

#include <string.h>
#include <stdio.h>
int strcmp(const char *str1,const char *str2 );

// I am trying to make a program that asks the user to input an answer 
int main() 
{
    char answer[20];


    printf("Can birds fly?\n");   
    scanf("%s", &answer[20]);    


    if(strcmp(answer, "yes") == 0)  
    {
        printf("You are right"); 
    }else
    {
        printf("You are worng"); 
    }

    return 0; 
}

最佳答案

更改此行:

scanf("%s", &answer[20]); 

至:

scanf("%s", answer);

您必须将要放置字符串的地址传递给 scanf,使用 answer[20] 选择字符串中第 21 个字符的值 (未定义,因为该字符串只有 20 个字符),然后获取指向它的指针(垃圾,您甚至可能会遇到访问冲突)。

关于c - 这个程序中的strcmp有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13651557/

相关文章:

C:比较结构中的两个字符串

c - strcmp 不工作

C范围问题

c - 了解解析 SVG 文件格式

使用 strcmp 和嵌套循环检查数组的值

c++ - 字符串的值不同,但打印它们显示相同的值

c++ - netlink 接口(interface) stat goto 交叉初始化错误

c++ - 二维数组(矩阵)中的错误访问错误

c - 如何在字符串数组中查找重复的字符串

c - 分割。 strcmp [C]