【问题标题】:Input comparison does not work properly, always going to the failure case, why?输入比较不能正常工作,总是去失败的情况,为什么?
【发布时间】:2014-01-09 19:48:06
【问题描述】:

在我的 C 程序中,我尝试使用 scanf 从控制台获取字符串 (char*) 输入,但是,无论输入什么,输入总是变成值 1638238

#include <stdio.h>
int main(void){
    for(;;){
        printf("Choose your option:\n-d for decryption\n-e for encryption\n");
        char command[2];
        char* input = command;
        scanf("%s", input);
        if(command == "-d"){
            printf("Please enter the path of the file\n");
            // decrypt
        }
        else if(command == "-e"){
            printf("Please enter the path of the file\n");
            // encrypt
        }
        else{
            printf("Unrecognized command '%d'\n", command);
        }
    }
}

例子:

输入:-e

输出:无法识别的命令“1638238”

编译器:Tiny C


编辑:我可以输入任何东西,它会输出

请输入要解密的文件路径`

#include <stdio.h>
#include <string.h>
int main(void){
    for(;;){
        printf("Choose your option:\n-d for decryption\n-e for encryption\n");
        char command[3];
        char* input = command;
        scanf("%s", input);
        if(strcmp(input, "-d")){
            printf("Please enter the path of the file to be decrypted\n");
        }
        else if(strcmp(input, "-e")){
            printf("Please enter the path of the file to be encrypted\n");
        }
        else{
            printf("Unrecognized command '%d'\n", input);
        }
    }
}

【问题讨论】:

  • 使用strcmp 比较字符串。和char command[3]

标签: c pointers if-statement scanf


【解决方案1】:

if(command == "-d")。一点也不。

command 指的是数组的基地址。您想要的是比较这些数组的 内容,而不是它们的 address 位置。

您可能想使用strcmp()。检查here

注意事项:要将char 数组用作字符串,您需要有一个终止\0 [NULL] 字符。请改用char command[3];


编辑:

为了解决更新代码中的问题,(复制到下面cmets的答案中)

  1. strcmp() 在匹配的情况下返回0。所以,要确定“匹配条件”,需要使用if (!strcmp(str1,str2))形式(注意!)。

  2. 为避免较长输入导致缓冲区溢出的可能性,请使用将输入限制为scanf()

    scanf("%2s", input);  //when input is a 3 element char array
    
  3. 我希望你意识到你的for(;;) 循环是一个绝对的无限循环,因为你没有任何breaking 语句。根据您方便的逻辑尝试添加一个。

【讨论】:

  • 由于使用strcmp 出现的另一个问题,我已经编辑了我的答案。如果您能帮助我,我将不胜感激。
  • @Joe -d-e 将转到最后一个 else, Unrecognized command ,所有其他输入将带您到 Please enter the path of the file to be decrypted。猜这不是你想要的。也许将!strcmp 一起使用?
【解决方案2】:

要比较字符串,请使用strcmpcommand == "-e" 是一种错误的比较方式。 command 衰减为指向输入第一个元素的指针。通过command == "-e",您将指针与字符串进行比较。

【讨论】:

    猜你喜欢
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 2020-10-05
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    相关资源
    最近更新 更多