I'm having some problems with the 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
scanf_s(" %c", &valinta, 1);
Adding a space before "%c"
will help should code call 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."
C11dr §K.3.5.3.2 4
Recommend dropping fflush(stdin);
as it is non-portable and may/may not work as expected.