2012-09-17 33 views
2

我正在從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(); 
} 
+1

相同的問題這看起來不像C++。將來,請標記C或C++,因爲這兩種語言都可以有不同的風格來完成您的任務。 – Marlon

+0

真的很難理解你的問題是什麼。 「它跳過標準輸入的第一個讀數」究竟意味着什麼? (你的問題有99%的可能性是有人輸入「Y enter」,而你只讀取一個字符,下一次調用'getchar'時留下回車。使用讀取行的函數。) –

+0

這看起來像一個家庭作業問題。家庭作業問題可以獲得作業標籤。我很確定它是,所以我會繼續爲你添加它。如果你不同意,你可以自己刪除它。編輯:呃,obselete並在被刪除的過程? *去元* – Wug

回答

2

的問題是,scanf()留下一個換行符輸入流中,你要使用它,你會得到「有效的」數據之前在getchar()

例:

scanf("\n%s",NewStud[count].name); 
getchar(); 
printf("\nAge : ");  
scanf("%d",&NewStud[count].age); 
getchar(); 
printf("Would you like to continue? (Y/N)"); 
test=getchar(); // Now this will work 

看看這個link獲取更多信息。這是爲fgets,但它與getchar()

0

比較test值與 '\ n',像這樣的例子:

int main() { 
    int test; 
    test = getchar(); 
    printf("[%d]\n", test); 
    if(test == '\n') printf("Enter pressed.\n"); 
    return(0); 
} 

PS:你test必須int

+0

getchar()返回一個字符,並且'\ 0'是一個字符,所以沒有理由使用int。 OP沒有說她的測試失敗了,只是爲了循環的第一次迭代。 – Mike

+1

@Mike C標準庫中的'getchar()'返回一個'int'。它不能返回'char',因爲它必須能夠區分一個有效字符的EOF條件。 –

0

當然它跳過了一讀,你把它放在一個if語句,像這樣:if(test=='\n')

你得到了所有對於某些學生的信息,然後按下用戶輸入,讓你去備份到for(count=0;count<5;count++)並要求爲新學生提供新的輸入。 我認爲你想要做的是使用while語句代替。

0

您可以取代

> test=getchar(); 
>  if(test=='\n') 
>  { 
>   printf("Invalid input. Would you like to continue? (Y/N)"); 
>   test=getchar(); 
>  } 

while((test=getchar()) == '\n') 
{ 
    printf("Invalid input. Would you like to continue? (Y/N)"); 
}