【发布时间】:2012-09-17 18:17:32
【问题描述】:
我正在阅读结构数组中的标准输入学生。在为一个学生介绍了详细信息后,我询问了另一个学生的详细信息。如果选择是Y,我会添加新学生,如果选择是N,break。但是,如果选择只是 ENTER 怎么办?如何检测换行符?我尝试使用 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++,因为这两种语言可以有不同的风格来完成您的任务。
-
很难理解你的问题是什么。 “它跳过标准输入的第一次阅读”到底是什么意思? (您的问题有 99% 的可能性是有人键入“Y enter”并且您只读取了一个字符,而在您下次调用
getchar时让 enter 读取。使用读取行的函数。) -
这看起来像是一道作业题。作业问题得到作业标签。我很确定它是,所以我会继续为你添加它。如果您不同意,您可以自行删除。编辑:呃,已经过时并且正在被删除? 转到元
-
@DavidSchwartz - 如果我错了,劳拉可以纠正我,但我很确定问题是显示提示“...(Y/N)”,然后它就正确了离开“无效输入”消息。由于使用
scanf(),导致输入缓冲区中留下了'\n'
标签: c