1

ユーザーに何度でも数字を入力させようとしています(そして、数字ごとにリンクリストノードを作成します)。

ただし、文字入力バッファをクリアする複数の方法を試しましたが、役に立ちませんでした。奇妙なことに、コードは 1 回実行されますが、2 回目は正しく実行されません。

たとえば、以下のコードでは、端末は次のように読み取ります。

would you like to enter an integer?
y
Enter an integer: 4
would you like to enter an integer?
y
**program terminates**

以前scanf("%c", yesno);は、最後の行に「y」を入力することさえできませんでした。終了したばかりです。

struct node *read_numbers(void){
    struct node *first = NULL;
    int n; char yesno;
    yesno = 'y';
    while( yesno == 'y'){
        printf("Would you like enter an integer ((y) for yes/(n) for no):\n");
        yesno = getchar();  
        while(getchar() != '\n');
        if(yesno == 'y'){
            printf("Enter an Integer:");
            scanf(" %d", &n);
            first = add_to_list(first, n);
            } else {
                return first;
                }
        } // end while
    }

文字入力とバッファについて調べたところ、おそらく getchar() メソッドが機能するはずです。私はそれを間違って使用していますか?また、「%c」の前後に余分なスペースを入れて scanf() を試しましたが、役に立ちませんでした。

4

3 に答える 3

2

andのより安全な代替手段としてfgetsを使用することをお勧めしますか?getcharscanf

お気づきのように、これらの関数は改行をバッファリングして、標準入力から読み取る次の関数に渡すことができます。

fgets入力を char 配列に格納して、このような問題を回避できます。さらに、入力が改行のみで構成されているかどうかを簡単に確認できます。

char user_input[10] = "";

printf("Would you like enter an integer ((y) for yes/(n) for no):\n");

/* get input or quit if only newline is entered, we only check the first char */
while(fgets(user_input, 3, stdin)[0] != '\n') 
{
    /* check if the first char is 'y', quicker to do than using strcmp */
    if(user_input[0] == 'y') 
    {
        int input = 0;

        printf("Enter an Integer: ");

        fgets(user_input, 5, stdin); /* get input again */

        input = atoi(user_input);    /* convert to int */

        printf("Your integer is %d\n", input);

        printf("Would you like to go again? y/n:\n");
    }
    else
    {
        return printf("No input there.\n");
    }
}
于 2013-06-04T02:10:20.560 に答える
1

getcharwhile(getchar() != '\n');標準入力バッファをクリアするのと同じように、標準入力からデータを取得します。したがって、次のコードは正しく機能します

于 2013-06-04T02:07:58.200 に答える