无法从用户那里获取两个输入

标签 c

我正在练习文件 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/

相关文章:

c - 如何正确使用从函数接收的指针? (在 C 中)

c - if else 语句问题

c - 分配后它不会是相同的内存地址吗?

c++ - 从 void* 到 void(*)(void*)[-fpermissive] 的无效转换

android - 将 uuid.h 包含到 Android NDK 项目中

c - 如何在 C 中实现作用域枚举

c - 第一次创建Stack。一行打印两次。为什么?

c - 等待单个对象 : do not lock a mutex but check the current state?

c - 如何显示 hh :mm:ss:SSS format in C 中耗时

c - C中奇怪的指针问题