C语言怎么实现输错了 重新输入

2025-03-10 19:31:58
推荐回答(3个)
回答1:

可以设置一个while循环在其体内输入数据,经判断输入正确则跳出循环,否则提示重新输入,直到输入正确。举例代码如下:

//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdio.h"
int main(void){
    int m[12]={31,28,31,30,31,30,31,31,30,31,30,31},year,month;
    while(1){//这个循环就是解决输入错误的
        printf("Please enter the year & month...\n");
        fflush(stdin);
        if(scanf("%d%d",&year,&month) && year>0 && month>0 && month<13)
            break;
        printf("Error, redo: ");
    }
    m[1]+=year%4==0 && year%100!=0 || year%400==0;
    printf("%d/%d is %d days.\n",month,year,m[month-1]);
    return 0;
}

回答2:

#include
using namespace std;
void main()
{
int month;
cout<<"请输入月份"< cin>>month;
switch(month)
{
case 1:
cout<<"2003年"< break;
case 2:
cout<<"2003年"< break;
case 3:
cout<<"2003年"< break;
case 4:
cout<<"2003年"< break;
case 5:
cout<<"2003年"< break;
case 6:
cout<<"2003年"< break;
case 7:
cout<<"2003年"< break;
case 8:
cout<<"2003年"< break;
case 9:
cout<<"2003年"< break;
case 10:
cout<<"2003年"< break;
case 11:
cout<<"2003年"< break;
case 12:
cout<<"2003年"< break;
default:
cout<<"fault"< break;
}
}

回答3:

设个标志位,用循环来实现。

伪代码如下:
/* ======= 代码开始 ======= */
int isOutOfRange;
Do
{
提示用户输入月份;
if (月份超出范围)
{
isOutOfRange = 1;
提示"fault";
}
else
isOutOfRange = 0;
}
while (isOutOfRange == 1)

输出2003年该月有几天;
/* ======= 代码结束 ======= */