[英]Can't get scanf_s or switch working
I'm having some problems with the scanf_s(); 我在scanf_s()中遇到了一些问题; function or the switch function, the first time I run my code it doesn't recognize the correct char and loops back to the beginning, but after that it works just fine.
函数或切换函数,当我第一次运行代码时,它无法识别正确的字符并循环回到开头,但是之后就可以正常工作了。 It is a simple calculator.
这是一个简单的计算器。
There probably is some easy solution to this since I have just started learning programming, but I can't find it. 由于我刚刚开始学习编程,因此可能有一些简单的解决方案,但找不到。
All the text is in Finnish, but I hope the code itself is understandable. 所有文字均为芬兰语,但我希望代码本身可以理解。
All feedback is welcome since I am eager to learn what I should and shouldn't do. 欢迎大家提供所有反馈,因为我渴望学习应该做和不应该做的事情。
#include <stdio.h>
#include <stdlib.h>
float luku1 = 0;
float luku2 = 0;
float tulos = 0;
char valinta = '\0';
int main()
{
system("cls");
printf("Minkä laskusuorituksen haluaisit tehdä? (+,-,*,/)\n");
fflush(stdin);
scanf_s("%c", &valinta);
switch (valinta){
case '+':
printf("Anna yhteenlaskettavat luvut.\n>");
scanf_s("%f %f", &luku1, &luku2);
tulos = luku1 + luku2;
printf("Lukujen summa on %4.2f\n", tulos);
break;
case '-':
printf("Anna vähennettävät luvut.\n>");
scanf_s("%f %f", &luku1, &luku2);
tulos = luku1 - luku2;
printf("Lukujen summa on %4.2f\n", tulos);
break;
case '*':
printf("Anna kerrottavat luvut.\n>");
scanf_s("%f %f", &luku1, &luku2);
tulos = luku1 * luku2;
printf("Lukujen tulo on %4.2f\n", tulos);
break;
case '/':
printf("Anna jaettavat luvut.\n>");
scanf_s("%f %f", &luku1, &luku2);
if (luku2 == 0)
{
printf("Nollalla ei voida jakaa.\n");
system("pause");
main();
}
else
{
tulos = luku1 / luku2;
printf("Lukujen jako on %4.2f\n", tulos);
}
break;
default:
printf("En tunnistanut laskutoimitusta, yritä uudelleen.\n");
system("pause");
main();
break;
}
}
scanf_s("%c", &valinta);
need another parameter. 需要另一个参数。 @mafso
@mafso
scanf_s(" %c", &valinta, 1);
Adding a space before "%c"
will help should code call scanf_s(" %c", &valinta);
在代码
"%c"
之前添加一个空格将有助于scanf_s(" %c", &valinta);
again. 再次。
"The fscanf_s function is equivalent to fscanf except that the c , s, and [ conversion specifiers apply to a pair of arguments (unless assignment suppression is indicated by a *). The first of these arguments is the same as for fscanf. That argument is immediately followed in the argument list by the second argument, which has type rsize_t and gives the number of elements in the array pointed to by the first argument of the pair." “ fscanf_s函数等效于fscanf,不同之处在于c ,s和[转换说明符适用于一对参数(除非分配抑制用*表示)。这些参数中的第一个与fscanf相同。该参数在参数列表中紧随其后的是第二个参数,其类型为rsize_t,并给出该对中第一个参数所指向的数组中的元素数。”
C11dr §K.3.5.3.2 4 C11dr§K.3.5.3.24
Recommend dropping fflush(stdin);
推荐
fflush(stdin);
as it is non-portable and may/may not work as expected. 因为它是不可携带的,并且可能/可能无法按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.