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

时间:2013-10-16 01:45:17

标签: 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);
    }

}

4 个答案:

答案 0 :(得分:6)

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

#include <string.h>

然后你可以使用

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

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

第三,CSVTSV变量永远不会给出值。使用

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

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

答案 1 :(得分:3)

以下是您需要进行的更改:

   printf("What output format would you like? (CSV,TSV/XML) ");
   scanf("%s", &output);
   ...


   if (strcmp(output, "CSV") == 0) {
   // ...
   } else if (strcmp(output, "TSV") == 0) {
   // ...
   }

答案 2 :(得分:2)

在C中,您使用strcmp(...)执行字符串相等性检查。

此外,字符串文字必须用引号"括起来。

#include <string.h>
// ...
if (strcmp(output, "CSV") == 0) {
  // ...
} else if (strcmp(output, "TSV") == 0) {
  // ...
}

[编辑] 如果您尝试使用整数来表示这些值(CSV,TSV,XML),那么您应该执行以下操作:

const int CSV = 1;
const int TSV = 2;
const int XML = 3;
// ...
printf("What output format would you like? (CSV=1,TSV=2,XML=3) ");
scanf("%d", &output);
// ...
if (output == 1/*CSV*/) {
  // ...
} else if (output == 2/*TSV*/) {
  // ...
}

答案 3 :(得分:1)

int output;
/* ... */
printf("What output format would you like? (CSV,TSV/XML) ");
scanf("%d", &output);

您要求用户输入CSVTSVXML,但之后您会读取整数,其有效必须是可选的+-后跟一系列十进制数字。

if (output == 'CSV') {

'CSV'是一个多字符常量。它的类型为int,并且具有实现定义的值。该值与用户在上一个提示中输入的内容无关。

(不幸的是,这个编译没有错误。多字符常量几乎没用。)

您可以为CSVTSVXML分配号码,向用户显示这些号码,读取数字输入,然后进行比较。例如:

const int CSV = 1;
const int TSV = 2;
const int XML = 3;
printf("What output format would you like? (CSV,TSV/XML) ");
scanf("%d", &output); /* error checking omitted for now */
if (output == CSV) {
    /* ... */
}
else if (output == TSV) {
    /* ... */
}
/* ... */

或者您可以将output更改为字符或字符串,读取(使用适当的scanf格式),然后将output与字符或字符串进行比较。< / p>

请注意,如果您使用字符串,则需要使用strcmp()而不是==来比较它们。

请务必检查scanf返回的值。它返回它能够扫描的项目数。对于您正在使用的调用,如果scanf返回的值不是1,则表示存在某种错误(例如,当您期望整数时,用户键入foo),并且您需要报告错误并可能退出程序 - 或者可能使用循环继续提示用户,直到您获得有效的内容。

相关问题