微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用C中的循环多次询问用户输入

如何解决使用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,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
}

代码运行一次,要求用户输入,然后完成

enter image description here

有人知道错误在哪里吗?谢谢你的建议

解决方法

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);  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。