【问题标题】:I'm trying to execute this code on Vscode but whenever I'm running this it's not taking the value of character but just showing a random number我正在尝试在 Vscode 上执行此代码,但每当我运行此代码时,它不会获取字符的值,而只是显示一个随机数
【发布时间】:2021-05-15 13:12:55
【问题描述】:

我是在线编码和学习 C++ 的新手,但是在运行此代码时,它不会获取字符的值。如果使用 cin 或 cout 它工作正常,但 scanf 给我带来了问题。有人可以用最基本的方式解释我做错了什么

    #include<iostream>
    #include<cstdio>
    #int main(){

    int num1, num2;
    char oper;

    printf("The first number is: ");
    scanf("%d", &num1);
    printf("The second number is: ");
    scanf("%d", &num2);
    printf("The operation you want to perform is: ");
    scanf("%c", &oper);

    if(oper == '+'){
        int total= num1+num2;
        printf("%i", &total);
    }

    else if(oper == '*'){
        int mul= num1 * num2;
        printf("%d", &mul);
    }

    else{
        int diff = num1-num2;
        printf("%d", &diff);
    }

    return 0;
}

【问题讨论】:

  • PS D:\C, C++ Projects\C++> cd "d:\C, C++ Projects\C++\" ; if ($?) { g++ sharma.cpp -o sharma } ; if ($?) { .\sharma } 第一个数字是:54 第二个数字是:45 你要执行的操作是:6422280 这是这个的输出
  • #int main(){你打错字了
  • 您期待什么?附:这看起来更像是 C 而不是 C++
  • 两个注意事项:#include &lt;iostream&gt; 在这里什么都不做,因为代码不使用该标头中的任何内容。而#include &lt;cstdio&gt; 将名称(printfscanf 是这里使用的名称)放在命名空间 std 中,它可能也将它们放在全局命名空间中。对于直接 C像这样的代码,使用#include &lt;stdio.h&gt;。或者,用&lt;cstdio&gt;,写std::printfstd::scanf

标签: c++


【解决方案1】:
  • 您在int main() 之前有一个额外的#
  • %d 在读取的数字后留下换行符,%c 将读取它,如果它在那里。您应该在 %c 之前添加一个空格字符以使 scanf() 空格字符(包括换行符)使其忽略空格字符。
  • %i%d 中的 printf() 需要 int。在那里传递int* 会调用未定义的行为

固定代码:

#include<iostream>
#include<cstdio>
int main(){ // remove extra #

    int num1, num2;
    char oper;

    printf("The first number is: ");
    scanf("%d", &num1);
    printf("The second number is: ");
    scanf("%d", &num2);
    printf("The operation you want to perform is: ");
    scanf(" %c", &oper); // add a space

    if(oper == '+'){
        int total= num1+num2;
        printf("%i", total); // pass the number itself, not a pointer
    }

    else if(oper == '*'){
        int mul= num1 * num2;
        printf("%d", mul); // pass the number itself, not a pointer
    }

    else{
        int diff = num1-num2;
        printf("%d", diff); // pass the number itself, not a pointer
    }

    return 0;
}

此外,如果您添加一些代码来检查 scanf() 的返回值以检查它们是否成功读取预期内容,您的代码会更好。

【讨论】:

    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 2018-12-09
    • 2020-10-11
    • 2018-10-07
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多