在if条件下改变字符串变量 [英] Varying string variable in an if condition

查看:103
本文介绍了在if条件下改变字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此程序将输入mm作为一年中的月份并打印出月份名称:

I used this program to take input mm as the month of the year and print out the name of the month:

#include <stdio.h>
#include <string.h>
int main(){
int mm;
printf("input month ");
scanf("%d", &mm);
char mname[9];
if (mm == 1) {mname = "January";}
if (mm == 2) {mname = "February";}
if (mm == 3) {mname = "March";}
if (mm == 4) {mname = "April";}
if (mm == 5) {mname = "May";}
if (mm == 6) {mname = "June";}
if (mm == 7) {mname = "July";}
if (mm == 8) {mname = "August";}
if (mm == 9) {mname = "September";}
if (mm == 10) {mname = "October";}
if (mm == 11) {mname = "November";}
if (mm == 12) {mname = "December";}
printf("%d is month %s", mm, mname);

return 0;
}

它给数组类型的表达式分配了错误。请帮助

it gave an error assignment to expression with array type. please help

推荐答案

接受 Michael Walz 两条很好的评论,并将其添加为答案:

Taking Michael Walz two great comments and adding them as an answer:

#include <stdio.h>
#include <string.h>

void main(int argc, char** argv)
{
    int mm = 0;

    printf("Please enter a month number [1-12]:\n");
    scanf("%d", &mm);
    static const char* months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

    if (mm >= 1 && mm <= 12)
    {
        printf("%d is month %s", mm, months[mm - 1]);
    }
    else
    {   
        printf("You have entered an invalid month number %d\n", mm);
    }
}

已进行了有效性检查(在上面的评论中提到)。

Validity check was done (mentioned in above comments).

希望有帮助。

干杯,

人。

这篇关于在if条件下改变字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆