0

我做了一个循环,不要一次又一次地重复一切。但是每当我尝试输入我的名字时,它都不允许我处理取消。这个怎么做?

int new_acc(FILE * fp, char *name, size_t namesize, char *dob, size_t dobsize){
    int one_by_one;
    char listing[8][15] = {"Name","Date of birth"};
    char another_list[8][15]  = {"name","dob"};         //   These two
    char list_size[8][15] = {"namesize","dobsize"};    //    lines are having problem.

    for (int i=0; i<one_by_one; i++){
        printf("Enter your %s: ",listing + i);
        fgets(another_list + i, list_size, stdin);
    }

    /* This is without loop printing */
    printf("Enter your name: ");
    fgets(name, namesize, stdin);
    fputs(name, fp);

    printf("Enter your Date of Birth: ");
    fgets(dob, dobsize, stdin);
    fputs(dob, fp);

    fclose(fp);

    return 0;
}
4

1 回答 1

1

这个数组有 8 行 14 + 空终止字符的空间,所以在设置 `ono_by_one 变量时必须小心,顺便说一下,它是未初始化的,这也是一个问题。

> 1它应该用一个值和初始化< 8

也不需要初始化它,因为您将覆盖存储在那里的字符串,使其:

char another_list[8][15];

这一行:

fgets(another_list + i, list_size, stdin);

不正确,第二个参数期望读取字符串的大小,它应该不大于将要存储它的容器,所以它应该看起来像:

fgets(another_list[i], sizeof(another_list[i]), stdin);

这一行:

printf("Enter your %s: ",listing + i);

没有多大意义,因为列表只有 2 行,所以one_by_one应该不大于 2。它将"Name"在第一次迭代和"Date of birth"第二次迭代中打印,然后什么也没有,或者它在它将读取的内存中找到的任何垃圾,这是未定义的行为。

所以整个代码应该是:

int new_acc(FILE * fp, char *name, size_t namesize, char *dob, size_t dobsize){

    int one_by_one = 8;
    char listing[][15] = {"Name","Date of birth"}; //the number of line can be ommited
    char another_list[8][15];
    char list_size[8][15] = {"namesize","dobsize"};

    for (int i=0; i< one_by_one; i++){
        printf("Enter your %s: ",listing + i); // needs to be changed
        fgets(another_list[i], sizeof(another_list[i]), stdin);
    }

    //here I can't help since I don't know the state of the arguments you 
    //will be passing to the funnction
    printf("Enter your name: ");
    fgets(name, namesize, stdin);
    fputs(name, fp);

    printf("Enter your Date of Birth: ");
    fgets(dob, dobsize, stdin);
    fputs(dob, fp);

    fclose(fp);

    return 0;
}
于 2020-05-10T00:13:49.873 回答