我正在练习文件I / O。编写了一个示例程序,从用户那里获取人员数据,并将其作为格式数据存储在.txt文件中,因此我可以将其用于内部搜索等。这是我的代码:typedef struct{ uchar personelNo[20]; uchar department[40]; uchar name[20]; uchar lastname[20];}Personel;void add_personnel() { FILE* f = fopen(FILE_NAME, "a+"); Personel temp; check("Enter personel name: ", temp.name, 1); check("Enter personel surname: ", temp.lastname, 1); check("Enter personel department: ", temp.department, 1); fprintf(f, "%d\t%s\t%s\t%s\n", get_last_p_number(f)+1, temp.name, temp.lastname, temp.department);}void error_function(const char* buffer, int no_conversions, char *additional_info) { fprintf(stderr, "Something went wrong. Here: %s , You entered:\n%s\n", additional_info ,buffer); fprintf(stderr, "%d successful", no_conversions); exit(EXIT_FAILURE);}void check(uchar* print_string, uchar* to_be_written, int buffer_size) { int r; char temps[BUFF_SIZE]; fprintf(stdout, "%s", print_string); //fflush(stdout); if (fgets(temps, BUFF_SIZE, stdin) == NULL) error_function(temps, 0, "fgets"); if ((r = sscanf(temps, " %s", to_be_written)) != buffer_size) error_function(temps, r, "sscanf");}int main(){ int selection; welcome_screen(); fprintf(stdout, "%s", "Enter your selection: "); scanf(" %d", &selection); if (selection == 1) { add_personnel(); }}当我尝试运行时,它运行正常,可以得到我的welcome_screen函数,并且当程序要求选择时。但是,当我键入我的选择时,它会立即退出,并显示如下输出:Enter personel name: Something went wrong. Here: sscanf , You entered:-1 successful是的,我什至无法弄清楚我的错误功能告诉了我什么。有谁知道这是什么问题?我以为是要刷新缓冲区,但是尝试时却无济于事。*编辑:忘记添加add_personel函数,现在在这里。 最佳答案 当error_function()是(r = sscanf(temps, " %s", to_be_written)) != buffer_size时,将调用false。您将temps,r和"sscanf"传递给error_function(),并且错误输出指示temps是空字符串或仅包含空格,并且r == -1指示在为空或只有空格。出现此问题的原因是使用temps格式说明符进行了更早的scanf()调用。当您输入时:1<newline>%d仅消耗%d位,保留1缓冲,随后由随后的<newline>调用提取。为确保您消耗(并丢弃)fgets()条目后面的所有非数字字符-读取所有字符,直到selection:scanf( "%d", &selection ) ;int discard = 0;do{ discard == getchar() ; } while( discard != '\n' && discard != EOF ) ;关于c - 无法从用户获得两个输入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59502554/
10-11 21:03