【发布时间】:2020-12-03 03:24:41
【问题描述】:
我希望 scanf 读取一些数据并将其存储到多个变量中。但是,如果第一个变量,即数量为 0,则 scanf 需要退出询问用户输入,因为我的后续 while 循环取决于该值,即数量。如果值不为零,则继续循环并做进一步的工作,否则不要。
#include <stdio.h>
struct inventory {
int quantity, category;
double price, soldByWeight;
char name[20];
};
void main(void) {
struct inventory arr[5] = { 0 };
printf("Enter values: \n");
for (int i = 0; i < 5; i++) {
scanf("%d%*c%d%*c%lf%*c%lf%*c%19[^\n]", &arr[i].quantity, &arr[i].category, &arr[i].price, &arr[i].soldByWeight, arr[i].name);
/*while (arr[i].quantity != 0) {
do some stuff
}*/
}
return 0;
}
样本输入 1:21,1,1.5,1,potato
样本输入 2:0
在示例输入 2 之后,如果我输入 0 并按 enter 键,scanf 仍在等待用户输入。输入 0 和回车键后如何退出 scanf 功能。 %*c 用于刷新示例输入中使用的逗号。
【问题讨论】:
标签: c