简体   繁体   English

奇怪的 output 编号(C)

[英]strange output number ( C )

#include<stdio.h>

int main(void)

{

    int h;
    int m;
    scanf_s("%d : %d", &h,&m);
    printf("%d : %d", h,m);

    return 0;
}

That is it, I typed 12 13 It gave me 12: -858993460就是这样,我输入了 12 13 它给了我 12:-858993460

ironic.. would you give me an idea?具有讽刺意味..你能给我一个主意吗?

If you typed exactly "12 13" as you wrote in the question, then the issue is that your input does not match the format specified in your call to scanf .如果您在问题中准确输入了“12 13”,那么问题是您的输入与您调用scanf时指定的格式不匹配。 In particular, scanf is only looking for input in the form of <some integer>: <some integer> .特别是, scanf只寻找<some integer>: <some integer>形式的输入。 Note that your input does NOT include the : character.请注意,您的输入不包括:字符。 As such, scanf only successfully reads a number into your first variable ( h ), but fails to read into the second variable ( m ).因此, scanf仅成功地将一个数字读入您的第一个变量 ( h ),但未能读入第二个变量 ( m )。

You can confirm this is the case by checking the return value of scanf , which returns "the number of input items successfully matched" (see the man page ).您可以通过检查scanf的返回值来确认这种情况,它返回“成功匹配的输入项的数量”(参见手册页)。

The reason you're seeing a "random" number in the output is that your variable m is never initialized.您在 output 中看到“随机”数字的原因是您的变量m从未初始化。 If you instead initialize it to 0 , then you will no longer see a "random" value.如果您改为将其初始化为0 ,那么您将不再看到“随机”值。 This is good practice anyway.无论如何,这是一个很好的做法。

For example (with error check):例如(带错误检查):

#include<stdio.h>

int main(void)

{

    int h = 0;
    int m = 0;
    int rc = scanf_s("%d : %d", &h,&m);
    if (rc != 2) { // expect to read 2 values
        printf("scanf failed, read %d value(s)\n", rc);
    } else {
        printf("%d : %d", h,m);
    }

    return 0;
}

Keep the format in scanf_s("%d: %d", &h,&m);将格式保留在scanf_s("%d: %d", &h,&m);

scanf() : The C library function int scanf(const char *format, ...) reads formatted input from stdin. scanf() : C 库 function int scanf(const char *format, ...)从标准输入读取格式化输入。

In your case, type 12: 13在你的情况下,输入 12: 13

Your call to the scanf_s function expects a colon in the input, but you didn't type one, so nothing got stored in m in the call.您对scanf_s function 的调用要求输入中有一个冒号,但您没有键入一个,因此在调用中没有任何内容存储在m中。 As a result, you got a garbage value for m (as you didn't initialize it either).结果,您得到了m的垃圾值(因为您也没有初始化它)。 If you type in 12: 13 , then you should get the expected result.如果您输入12: 13 ,那么您应该得到预期的结果。

Also, make sure to check the return value of scanf_s to make sure that you've got all of the values you want.此外,请务必检查scanf_s的返回值,以确保您获得了所有您想要的值。

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

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