[英]Asking for user's input multiple times with loop in C
有了这个初学者的代码,只要输入不是“退出”,我就会尝试要求用户输入。 我的代码:
void createReport(){
printf("Welcome to the report generator, type item's ID: ");
char *userInput;
int i=0;
struct myStruct{
char *name;
int id;
float sale;
};
struct myStruct *myStructArray[MAX_ITEMS];
fgets(userInput,sizeof(int),stdin);
while(strcmp(userInput,"quit")!=0) {
userInput = malloc(sizeof(int));
fgets(userInput,sizeof(int),stdin);
searchA(userInput); //different function that changes global variable deletion
printf("Added to the report, add more or type \'quit\' \n");
strcpy(myStructArray[i]->name,inventoryItem[deletion].name); //inventoryItem is global
myStructArray[i]->id = atoi(input);
myStructArray[i]->sale = inventoryItem[deletion].sale;
i++;
free(userInput);
}
for(int x=0;x<30;x++) printf(myStructArray[x]->name); //never executed
}
有谁知道错误在哪里? 感谢您的任何建议
在你做的while
循环之前
fgets(userInput,sizeof(int),stdin);
那时您的变量userInput
尚未设置。
代码思路运行示例:
printf("Welcome to the report generator, type item's ID: ");
const int input_size = 6 * sizeof(char);
char *userInput = malloc(input_size);
int i = 0;
struct myStruct {
char *name;
int id;
float sale;
};
struct myStruct *myStructArray[MAX_ITEMS];
fgets(userInput, input_size, stdin);
while (strcmp(userInput, "quit") != 0 && strcmp(userInput, "quit\n") != 0)
{
// do whatever you like with myStructArray[i], for example:
myStructArray[i] = malloc(sizeof(struct myStruct));
myStructArray[i]->name = malloc(sizeof(char));
myStructArray[i]->name = "ab";
myStructArray[i]->id = 7;
myStructArray[i]->sale = 99.9F;
printf("Added %s, %d, %f\n", myStructArray[i]->name, myStructArray[i]->id, myStructArray[i]->sale);
//prepare for next iteration:
printf("Added to the report, add more or type \'quit\' \n");
for (int j = 0; j < input_size; ++j) // zeroing allocated data on the heap
userInput[j] = 0;
fgets(userInput, input_size, stdin);
i++;
}
free(userInput);
for (int x = 0; x < i; x++) printf("%s,", myStructArray[x]->name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.