【问题标题】:What's wrong with strcmp in this program?这个程序中的 strcmp 有什么问题?
【发布时间】:2012-11-30 19:11:11
【问题描述】:

当我运行程序并回答“是”时,它告诉我我错了。有人知道执行这种程序的方法吗?

#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; 
}

【问题讨论】:

    标签: c strcmp


    【解决方案1】:

    改变这一行:

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

    到:

    scanf("%s", answer);
    

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

    【讨论】:

    • @user1867232 因为它有效,请考虑接受作为您问题的答案
    猜你喜欢
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多