【问题标题】:C language, giving value to char in an if-else statement?C 语言,在 if-else 语句中赋予 char 值?
【发布时间】:2016-02-21 12:36:13
【问题描述】:

我正在尝试像这样使用定义

`printf ("1st Account:");
scanf("%i",&AN1);
printf ("Value of 1st Account:");
scanf("%f",&VAN1);
printf ("2nd Account:");
scanf("%i",&AN2);
printf ("Value of 2nd Account:");
scanf("%f",&VAN2);
system("pause");
system("cls");
if (AN1==101)
#define CAN1 "Cash"
else if (AN1==102)
#define CAN1 "Accounts Receivable"
else if (AN1==104)
#define CAN1 "Notes Receivable"`

等等

显然,它不起作用,因为 define 是针对整个程序的,并且不是仅在 if 语句中读取的。

有人知道如何让它工作吗? 我需要稍后显示它,就像这样

`printf ("Your 1st account name is: %s with the value of %.2f.\n",CAN1,VAN1);
printf ("Your 2nd account name is: %s with the value of %.2f.\n",CAN2,VAN2);`

【问题讨论】:

    标签: c dev-c++


    【解决方案1】:

    使用变量而不是定义:

     const char *can1 ="unknown";
    
     if (AN1==101)
        can1 = "Cash";
    else if (AN1==102)
         can1 = "Accounts Receivable";
    else if (AN1==104)
        can1 = "Notes Receivable";
    

    define 在编译时处理,而你的值只在运行时知道。

    【讨论】:

      【解决方案2】:

      正如您正确观察到的,#define 语句和预处理器指令通常在编译前进行评估。预处理器处理文件,输出预处理后的文件,并将其传递给编译器,最终生成目标文件和/或可执行文件。
      预处理器没有范围、大括号、语法或语言结构的概念。它只是解析源文件,替换出现的宏,并执行其他元数据。

      作为替代,您可以使用字符串文字:

      const char* ptr;
      
      if (that)
          ptr = "that";
      else
          ptr = "else";
      

      字符串文字不能超出范围,因为它们存在于程序的整个运行时;它们通常存储在可执行文件的核心映像中。

      【讨论】:

        【解决方案3】:

        define 在编译时在预处理中处理。您不能在运行时有条件地定义事物。

        您可以将常量分配给指针:

        #include <stdio.h>
        
        int main(void) 
        {
        
        char *can1;
        int an1 = 0;
        
        if (an1 == 0) 
            can1 = "Cash";
        else if (an1 == 102)
            can1 = "Accounts Receivable";
        else if (an1 == 104)
            can1 = "Notes Receivable";
        
        printf("%s\n", can1);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-01-20
          • 1970-01-01
          • 1970-01-01
          • 2013-10-07
          • 1970-01-01
          • 1970-01-01
          • 2013-04-21
          • 2019-04-09
          相关资源
          最近更新 更多