我正在练习文件 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()
调用%d
格式说明符。当您输入:
1<newline>
%d
仅消耗 1
数字,留下 <newline>
缓冲并随后由后续 fgets()
提取打电话。
确保您使用(并丢弃)selection
后面的所有非数字字符。条目 - 读取所有字符,直到 <newline>
:
scanf( "%d", &selection ) ;
int discard = 0;
do{ discard == getchar() ; } while( discard != '\n' && discard != EOF ) ;
关于无法从用户那里获取两个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59502554/