C 扫描读数完全不同

C 扫描读数完全不同,c,scanf,C,Scanf,以下是我在Visual Studio中拥有的所有代码: #include <stdio.h> int main (void) { int input; puts("There are 10 seats available on the next flight"); puts("Where would you like to reserve a seat?"); puts("Please type 1 for First Class");

以下是我在Visual Studio中拥有的所有代码:

#include <stdio.h>

int main (void) {

    int input;

    puts("There are 10 seats available on the next flight");
    puts("Where would you like to reserve a seat?");
    puts("Please type 1 for First Class");
    puts("Please type 2 for Economy");

    scanf("%d", &input);

    if (input == 1) {
        printf("You Typed %d\n", &input);
    }
    if (input == 2) {
        printf("You Typed %d\n", &input);
    }

}

我每次都得到一个完全随机的数字。正因为如此,在输入工作之后,我似乎无法得到我所写的任何东西。为什么会发生这种情况?

打印出来的是变量
输入的地址,而不是它的值!这是因为printf通过值接受它的参数——仅仅因为它们可以这样传递。因此,你需要的是

printf("%d", input); // without the ampersand!
相比之下,scanf则完全不同。它将把一个值放入您提供给它的变量中,因此需要一个指针

简单的例子:

int n = 7;

void myPrintf(int v)
{
    ++v;
}

void myScanf(int* v)
{
    ++*v;
}

int main(int argc, char* argv[])
{
    myPrintf(n); // n passed by value, cannot be modified
                 // (but printf does not intend to, either!)
    myScanf(&n); // n will be incremented!
                 // (scanf does modify, thus needs a pointer)
    return 0;
}

不过,回到根上来:仍然存在一个基本问题:您传递的是一个指针,但将其作为int进行计算。如果两个指针的大小不同(在现代64位硬件上就是这种情况),您就有麻烦了。然后以不同的大小从堆栈中读取该值,并且您的部分地址实际上被丢弃(指针地址需要
“%p”
格式说明符,以确保从堆栈中读取适当数量的字节-在现代系统中,int是8,而int是4).

为什么要将指针与printf一起使用?不要将地址发送到
printf
,除非您有一个需要的格式说明符(而且您没有)。丢失上面最简单的:
printf(“您键入了%d\n”,&input)-->
printf(“您键入了%d\n”,输入)VTC作为打字错误。在我排除错误之前&现在我没有。所以现在它工作得很好。这很烦人。以前你的代码可能是错误地使用scanf而不是printf,现在不是了。
int n = 7;

void myPrintf(int v)
{
    ++v;
}

void myScanf(int* v)
{
    ++*v;
}

int main(int argc, char* argv[])
{
    myPrintf(n); // n passed by value, cannot be modified
                 // (but printf does not intend to, either!)
    myScanf(&n); // n will be incremented!
                 // (scanf does modify, thus needs a pointer)
    return 0;
}