Switch statement not doing what I expect

后端 未结 4 2126
悲&欢浪女
悲&欢浪女 2020-12-12 07:50

What is wrong with this code:

switch (n)
{
    case 0:   strcpy(resultString, \"Zero\");
    case 1:   strcpy(resultString, \"One\");
    case 2:   strcpy(re         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 08:18

    You need a break statement at the end of each case. Otherwise control falls straight through to the next case.

    Change your code to:

    switch (n)
    {
        case 0: strcpy(resultString, "Zero"); 
                break;
        case 1: strcpy(resultString, "One"); 
                break;
        case 2: strcpy(resultString, "Two"); 
                break;
        case 3: strcpy(resultString, "Three"); 
                break;
        case 4: strcpy(resultString, "Four"); 
                break;
        case 5: strcpy(resultString, "Five"); 
                break;
        case 6: strcpy(resultString, "Six"); 
                break;
        case 7: strcpy(resultString, "Seven"); 
                break;
        case 8: strcpy(resultString, "Eight"); 
                break;
        case 9: strcpy(resultString, "Nine"); 
                break;
    }
    printf("%s", resultString);
    

    You can find the switch statement documented here or in any book on the C language.

提交回复
热议问题