问题描述
使用此初学者的代码,只要输入未“退出”,我就会尝试要求用户输入。我的代码:
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,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,stdin);
i++;
}
free(userInput);
for (int x = 0; x < i; x++) printf("%s,",myStructArray[x]->name);