0
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 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.