私は構造体配列でstdinの学生から読んでいます。ある生徒の詳細を紹介した後、別の生徒の詳細を尋ねます。選択肢がYの場合は、新しい生徒を追加します。選択肢がNの場合は、中断します。しかし、選択が単にENTERである場合はどうなるでしょうか?改行文字を検出するにはどうすればよいですか?getchar()を試してみましたが、stdinからの最初の読み取りをスキップします。デバッグすると、最初の行test = getchar()で停止せず、2番目の行で停止します。
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>
struct student
{
char name[20];
int age;
};
int main()
{
struct student NewStud[5];
char test;
int count=0;
for(count=0;count<5;count++)
{
printf("Enter the details for %s student: ",count>0?"another":"a");
printf("\nName : ");
scanf("%s",NewStud[count].name);
printf("\nAge : ");
scanf("%d",&NewStud[count].age);
printf("Would you like to continue? (Y/N)");
test=getchar();
if(test=='\n')
{
printf("Invalid input. Would you like to continue? (Y/N)");
test=getchar();
}
while(tolower(test) !='n' && tolower(test) != 'y')
{
printf("Invalid input.Would you like to continue? (Y/N)");
test=getchar();
}
if(tolower(test) == 'n')
{
break;
}
if(tolower(test) == 'y')
{
continue;
}
}
getch();
}