我正在從stdin學生讀取一個結構數組。在爲一名學生介紹詳細信息之後,我要求提供另一個學生的詳細信息。如果選擇是Y,我會添加新學生,如果選擇是N,break。但是,如果選擇僅僅是回車呢?我如何檢測新行字符?我試着用getchar(),但是它跳過了stdin的第一次讀取。當我調試它不停止到第一行test = getchar()時,它停止到第二個。檢測一個新的行字符
#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();
}
相同的問題這看起來不像C++。將來,請標記C或C++,因爲這兩種語言都可以有不同的風格來完成您的任務。 – Marlon
真的很難理解你的問題是什麼。 「它跳過標準輸入的第一個讀數」究竟意味着什麼? (你的問題有99%的可能性是有人輸入「Y enter」,而你只讀取一個字符,下一次調用'getchar'時留下回車。使用讀取行的函數。) –
這看起來像一個家庭作業問題。家庭作業問題可以獲得作業標籤。我很確定它是,所以我會繼續爲你添加它。如果你不同意,你可以自己刪除它。編輯:呃,obselete並在被刪除的過程? *去元* – Wug