Using fgets() right after getchar()

ⅰ亾dé卋堺 提交于 2021-02-17 05:21:39

问题


void
read_stdin(trace_t* trace, state_t state, action_t** action_list) {
    // initial stage
    int c;
    while ((c = getchar())!= EOF && c!='#') {
        if (my_isalpha(c)==LOWERCASE) {
            state[c-ASCII_CODE_LOWER_A] = '1';
        }
    }
    printf("%s\n", state);

    char str[2];
    fgets(str, 2, stdin);
    printf("%s", str);
}

If '#' is the last character I enter in the getchar() loop, fgets() records the newline character from when I press enter and skips to the print statement immediately (which prints the '\n')

I could fix this by adding an additional fgets()(which has to have a string that is longer than 1 char passed to it for some reason?) but is there a more elegant way of solving this?


回答1:


Well, you can use scanf("%*[\n]"); to ignore any number of consecutive newline. Or scanf("%*1[\n]"); for eating only one newline. If any other character is the first one, it is not consumed.

Another option would be to use low-level operations getchar and ungetc:

int eat_stdin_newline(void) {
    int ch = getchar();
    if (ch != EOF && ch != '\n') {
        // if it wasn't EOF or newline, push it back...
        ungetc(ch, stdin); // must succeed
    }
    return ch;
}

Then you can call this function wherever you want:

eat_stdin_newline();


来源:https://stackoverflow.com/questions/64533626/using-fgets-right-after-getchar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!