在getchar()之后立即使用fgets() [英] Using fgets() right after getchar()

查看:76
本文介绍了在getchar()之后立即使用fgets()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  voidread_stdin(trace_t *跟踪,state_t状态,action_t ** action_list){//初期int c;while(((c = getchar())!= EOF& c!='#'){如果(my_isalpha(c)== LOWERCASE){状态[c-ASCII_CODE_LOWER_A] ='1';}}printf(%s \ n",状态);char str [2];fgets(str,2,stdin);printf(%s",str);} 

如果#"是我在getchar()循环中输入的最后一个字符,则fgets()记录我按Enter键时的换行符,并立即跳至print语句(打印"\ n")

我可以通过添加一个附加的fgets()(由于某种原因而必须将一个大于1个char的字符串传递给它)来解决此问题,但是有解决此问题的更优雅的方法吗?

解决方案

好,您可以使用 scanf(%* [\ n]"); 忽略任何数字连续的换行符.或 scanf(%* 1 [\ n]"); 只吃一个 换行符.如果第一个字符是其他任何字符,则不会使用.

另一种选择是使用低级操作 getchar ungetc :

  int eat_stdin_newline(void){int ch = getchar();if(ch!= EOF&&ch!='\ n'){//如果不是EOF或换行符,请将其推回...ungetc(ch,stdin);//必须成功}返回ch} 

然后您可以在任何需要的地方调用此函数:

  eat_stdin_newline(); 

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?

解决方案

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();

这篇关于在getchar()之后立即使用fgets()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆