c - 为什么这段代码不能识别任何 if 语句?

标签 c

<分区>

我的程序获取所有数据并询问您是否希望以 3 种不同的方式显示它。 CSV、TSV、XML。我添加了 2 个 if 语句,当试图让它们工作时,它会要求我选择我想要显示的设置,然后它会结束程序。这是为什么?

#include <stdio.h>
int main (int argc, char *argv[]) {
    int  phoneNumber;
    char firstName[11];
    char lastName[11];
    char eMail[20];
    int output;
    int CSV;
    int TSV;
    int XML;

    printf("Please enter the user's first name:");
    scanf("%s", firstName);
    printf("Please enter the user's last name:");
    scanf("%s", lastName);
    printf("Please enter the user's phone number:");
    scanf("%i", &phoneNumber);
    printf("Please enter the user's e-mail:");
    scanf("%s", eMail);
    printf("What output format would you like? (CSV,TSV/XML) ");
    scanf("%d", &output);

    if (output == 'CSV') {
        printf("firstName,lastName,phoneNumber,eMail");
        printf("%s,%s,%i,%s",firstName, lastName, phoneNumber, eMail);
    }
    else if (output == 'TSV') {
        printf("firstName,\tlastName,\tphoneNumber,\teMail");
        printf("%s,\t%s,\t%i,\t%s", firstName, lastName, phoneNumber, eMail);
    }

}

最佳答案

首先,如前所述,您需要使用strcmp 函数来比较字符串。 == 正在测试字符串是否与编译器生成的常量位于同一位置,但事实并非如此。

#include <string.h>

然后你就可以使用了

if(strcmp(output,"CSV")==0) { /*output CSV*/ }

其次,您需要使用 " 而不是 ' 来分隔字符串;' 仅适用于单个字符。

第三,CSVTSV 变量从未被赋予值。使用

char output[256];
scanf("%s", output)

然后您可以使用 strcmp(output, "CSV")(或 strcasecmp,具体取决于您是否需要区分大小写)。

关于c - 为什么这段代码不能识别任何 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393925/

相关文章:

c++ - 将 char 设置为 '\0' 会泄漏内存吗?

C 中表示指针大小的正确类型?

c - 从 MATLAB 调用的 C .exe 文件中存在的 fprintf() 不起作用

c - 在 C : prevent generating stack pointer initialization 中写入引导扇区

c - 使用 getchar 使用循环 c 代码丢弃除第一个字符之外的所有字符

ios - iOS 上的 char 是有符号的还是无符号的?

c - 读取一个大文件并将数据放在正确的数组中而不要太口头表达

java - 在 Java 中创建类似结构的数据结构

c - 最小化 malloc() 调用量可以提高性能?

c - 仅使用 C 中的循环回文