私のシステムでは、リターンキーを押すまでgetc()が戻ってこないようです。つまり、「Y」の後には常に「\n」が続きます。したがって、ループを継続するために、whileに条件を追加する必要がありました。
#include <stdio.h>
#include <ctype.h>
int main()
{
char n = 'Y';
while ( toupper(n) == 'Y' || n == '\n' )
{
if ( n != '\n' )
{
printf("Add Next Y/N: ");
}
n = getc(stdin);
}
}
fgets()の方がうまくいくようです:
#include <stdio.h>
#include <ctype.h>
int main()
{
char input[100] = { "Y" };
while ( toupper(input[0]) == 'Y' )
{
printf("Add Next Y/N: ");
fgets(input,sizeof(input),stdin);
}
}
以下のコメントを編集してください:scanf()にもキャリッジリターンの問題があります。fgets()、次にsscanf()の方が適しています。余分なgetchar()を実行しているので、'\n'のチェックを取り除くことができると思います。これを試して:
#include <stdio.h>
#include <ctype.h>
struct item {
char name[100];
int avg;
double cost;
};
int main()
{
FILE *fp = fopen("getc.txt","w");
struct item e;
char line[200];
char next = 'Y';
while(toupper(next) == 'Y')
{
printf("Model name, Average, Price: ");
fgets(line,sizeof(line),stdin);
sscanf(line,"%s %d %f",e.name,&e.avg,&e.cost);
fwrite(&e,sizeof(e),1,fp);
printf("Add Next (Y/N): ");
next = getc(stdin);
getchar(); // to get rid of the carriage return
}
fclose(fp);
}
sscanf()を使用しない別の方法:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
struct item {
char name[100];
int avg;
double cost;
};
int main()
{
struct item e;
char line[200];
char next = 'Y';
while(toupper(next) == 'Y')
{
printf("Model name ");
fgets(line,sizeof(line),stdin);
line[ strlen(line) - 1 ] = '\0'; // get rid of '\n'
strcpy(e.name,line);
printf("\nAverage ");
fgets(line,sizeof(line),stdin);
e.avg = atoi(line);
printf("\nPrice ");
fgets(line,sizeof(line),stdin);
e.cost = atof(line);
printf("you input %s %d %f\n",e.name,e.avg,e.cost);
printf("Add Next (Y/N): ");
next = getc(stdin);
getchar(); // get rid of carriage return
}
}