[英]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
I'm new to coding and learning C++ online but while running this code it just doesn't takes the value of the character.我是在线编码和学习 C++ 的新手,但是在运行此代码时,它只是不采用字符的值。 If using
cin
or cout it's working fine but scanf
is giving me problems.如果使用
cin
或 cout 它工作正常,但scanf
给我带来了问题。 Can someone explain me what am I doing wrong in the most basic way possible有人可以以最基本的方式向我解释我做错了什么吗
#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;
}
#
before int main()
.#
在int main()
之前。%d
leaves newline character after the number read and %c
will read it if it is there. %d
在读取的数字后留下换行符,如果存在, %c
将读取它。 You should add a space character befoer %c
to have scanf()
whitespace characters (including newline character) to have it ignore space characters.%c
之前添加一个空格字符以使其具有scanf()
空白字符(包括换行符)以使其忽略空格字符。%i
and %d
in printf()
expects int
. printf()
中的%i
和%d
需要int
。 Passing int*
there invokes undefined behavior .int*
会调用未定义的行为。 Fixed code:固定代码:
#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;
}
Also your code will be better if you add some code to check return values of scanf()
to check if they successfully read expected things.此外,如果您添加一些代码来检查
scanf()
的返回值以检查它们是否成功读取预期内容,您的代码也会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.