简体   繁体   English

C —不评估交换机中的多个Scanf语句

[英]C — Multiple Scanf Statements in a Switch Are Not Evaluated

I have a problem with some really basic C code for which I couldn't find a solution on any existing StackOverflow question. 我对一些非常基本的C代码有问题,无法在任何现有的StackOverflow问题上找到解决方案。

The problem is simple: I have two scanf statements inside two different cases of a switch statement. 问题很简单:我在switch语句的两种不同cases有两个scanf语句。 The first statement is executed perfectly every time. 第一条语句每次都会完美执行。 The second, however, doesn't work, no matter which case the switch is evaluating. 但是,无论switch在哪种情况下进行评估,第二种方法均不起作用。

Here's a tiny program I wrote to demonstrate the issue: 这是我编写的一个小程序来演示该问题:

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

int main(void)
{
int i = 0;

char *str1;
char *str2;
int state1, state2;
switch(i)
{
    case 0:
        state1 = scanf("%s", str1);
        getchar();
        break;
    case 1:
        state2 = scanf("%s", str2);
        getchar();
        break;
    default:
        printf("Something weird happened.\n");
        break;
    }
    printf("String 1: %s\nString 2: %s\nReturn 1: %d\nReturn 2: %d\n", str1, 
    str2, state1, state2); 

    return 0;
}

The getchar s are there to make sure it isn't an input overflow problem. 那里的getchar ,以确保它不是输入溢出问题。

If I run that with i = 0 with an input of "hello" then I get 如果我在输入"hello"i = 0进行运行,那么我得到

String 1: hello
String 2: (null)
Return 1: 1
Return 2: 4195648

If run with i = 1 and "hello" it outputs 如果以i = 1"hello"运行,则输出

String 1: 
String 2: (null)
Return 1: 0
Return 2: 0

As you can see, String 2 is never given a value despite running through that case . 如您所见,即使执行完case ,字符串2都不会得到值。

This, to me, implies that the switch statement somehow runs through every case up to the matching one without actually evaluating what's inside, since both state1 and state2 are 0 in the second instance. 对我来说,这意味着switch语句会在某种case一直运行到匹配的case ,而实际上并未评估其中的内容,因为在第二个实例中state1state2均为0。

Does anyone know why this happens and how I can fix this? 有谁知道为什么会这样以及我该如何解决?

the variable i is only set to 0, so only the switch/case 0: will be evaluated. 变量i仅设置为0,因此仅评估开关/情况0 :。

The switch statement is never re-entered and the value of i is never updated, so no other switch/case will ever be evaluated/executed. switch语句永远不会重新输入,并且i的值永远不会更新,因此不会评估/执行其他任何switch / case。

I suspect your idea of how a switch statement works is not quite correct. 我怀疑您对switch语句如何工作的想法不太正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM