if语句使用char字符串 - 将无法识别字符串

时间:2014-10-07 20:27:13

标签: c string if-statement char

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

int main()

{
    bool flag= true;
    int menu_option;
    char first_band [16], second_band [16], third_band [16], fourth_band [16], green[16];

    while (flag)
    {



    printf("Please choose an option:\n");
    printf("To run the program, enter 1.\n");
    printf("For help, enter 2.\n");
    printf("To exit, enter 3.\n");
    scanf("%i", &menu_option);


       switch (menu_option)

      {
        case 1:
            printf("Please enter the colour of the first band on the resistor:\n");
            scanf(" %s", first_band);
            printf("Please enter the colour of the second band on the resistor:\n");
            scanf(" %s", second_band);
            printf("Please enter the colour of the third band on the resistor:\n");
            scanf(" %s", third_band);
            printf("Please enter the colour to fourth band ont he resistor. If there is no fourth    band, enter 'null'.\n");
            scanf(" %s", fourth_band);
            flag=false;
            break;


        case 2:
           flag=true;
            printf("program instructions");
            break;

        case 3:
           flag=false;
            return 0;
            break;

        default:
            flag=true;
            printf("Invalid command.\n");
            break;
       }


   }

       printf("%s", first_band);

       if (first_band == "green")
           printf("the first band is %c\n", first_band);

 return (0);

}

所以我无法获得最后一个“if”语句来打印“第一个乐队是%s”。正上方的打印声明是看程序是否正在读取用户输入......它似乎是。它似乎不会识别该单词并执行if语句。我觉得在处理char字符串时我的语法是错误的,这导致了这个问题,但我是新手,所以非常感谢帮助之手。

1 个答案:

答案 0 :(得分:0)

您必须改为使用strcmp()

if (strcmp(first_band, "green") == 0)
           printf("the first band is %c\n", first_band);