以下に示す私のコードでは、「y」を1回押すと繰り返しますが、次のトメを繰り返すように求めていません(または「y」を押します)。
main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf("%c",&choice);
}while(choice=='y');
}
以下に示す私のコードでは、「y」を1回押すと繰り返しますが、次のトメを繰り返すように求めていません(または「y」を押します)。
main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf("%c",&choice);
}while(choice=='y');
}
scanf フォーマット文字列の最初の文字にスペースを挿入します。これにより、データを読み取る前に標準入力からすべての空白文字が消去されます。
#include <stdio.h>
int main (void)
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf(" %c",&choice); // note the space
}while(choice=='y');
return 0;
}
その scanf() 呼び出しの後に改行文字を読み上げる必要があります。それ以外の場合は、次回にそれが選択されるため、while ループが出てきます。
#include<stdio.h>
int main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
choice = getchar();
getchar();
}
while(choice=='y');
return 0;
}
これは、標準入力がバッファリングされているためです。したがって、おそらく a のy
後に a \n
(改行文字) の文字列を入力しています。
したがって、最初の反復は を受け取りますが、次の反復は標準入力バッファーの次であるy
ため、ユーザーからの入力は必要ありません。\n
しかし、scanf に末尾の空白を消費させることで、これを簡単に回避できます。
scanf("%c ",&choice);
注: c の後のスペース"%c "
ただし、入力が . で終わると、プログラムが無限ループに陥る可能性がありますy
。したがって、 の結果も確認する必要がありますscanf
。例えば
if( scanf("%c ",&choice) <= 0 )
choice = 'n';