我的程序在SCANF语句之后不起作用

My program isnt working after the scanf statement

本文关键字:之后 不起作用 语句 SCANF 程序 我的      更新时间:2023-10-16

我的代码在第二个SCANF语句之后无法正常工作。我还是C 的新手,所以我不确定我在做什么错。我和其他网站都在此网站上查看,到目前为止,还没有找到任何东西。我也尝试了FFLUSH语句,但这也没有解决,任何其他建议都非常感谢。

include <stdio.h>
int main(void)
{
    //Intro message
    printf("This program will take the order of a customer and then subtract their order from the inventory list. After calculations a new inventory list will appearn");
// declare variables
int dough, sauce, cheese, pepperoni, sausage, greenPeppers, blackOlives, mushrooms;
int num1; 
char pizza;
// create inventory
dough = 50;
sauce = 50;
cheese = 50;
pepperoni = 50;
sausage = 50;
greenPeppers = 50;
blackOlives = 50;
mushrooms = 50;
//display the inventory
printf("n The currrent inventory is: n Dough:%d", dough);
printf("n Sause:%d", sauce);
printf("n Cheese:%d", cheese);
printf("n Pepperoni:%d", pepperoni);
printf("n Sausage:%d", sausage);
printf("n Green Peppers:%d", greenPeppers);
printf("n Black Olives%d", blackOlives);
printf("n Mushrooms:%d", mushrooms);
//get customer input
printf("nWhat type of pizza would you like? Please type a lowercase letter and only chose one. Type C for Cheese, P for Pepperoni, S for Sausage, and V for Veggie.n");
scanf_s(" %c", &pizza);
 printf("nHow many pizzas would you like to order? Maximum of 10.n");
 scanf_s("  %d", &num1);
//This is where it stops
 printf("It cuts out here, why can I not see anything after this line?");

// calculate what inventory will be taken out
cheese = cheese - num1;
dough = dough - num1;
sauce = sauce - num1;
switch (pizza)
{
case 'c': 
    cheese = 50 - num1;
    break;
case 'p':
    pepperoni = pepperoni - num1;
    break;
case 's':
    sausage = sausage - num1;
    break;
case 'v':
    blackOlives = blackOlives - num1;
    greenPeppers = greenPeppers - num1;
    mushrooms = mushrooms - num1;
    break; 
}
// display final inventory
printf("The new inventory is: n Dough:%d", dough);
printf("n Sause:%d", sauce);
printf("n Cheese:%d", cheese);
printf("n Pepperoni:%d", pepperoni);
printf("n Sausage:%d", sausage);
printf("n Green Peppers:%d", greenPeppers);
printf("n Black Olives%d", blackOlives);
printf("n Mushrooms:%d", mushrooms);

return 0;
}

问题是您使用的是scanf(或其堂兄scanf_s(。scanf问题是不适合交互式输入的,导致您看到的结果令人困惑。

而是使用fgets函数将数据读取到字符数组中。如果您需要将该字符数组转换为一个数字,请使用atoi