我的C代码如下:
/*************************************************************************
******* Program to Calculate either Area or perimeter of given input ****
******* This program was created by Naveen Niraula and is under beta ****/
#include <stdio.h>
#include <conio.h>
#include <windows.h>
int main()
{
/***** Setting title of the console window *****/
SetConsoleTitle("Area or Primeter v 0.1 [beta]");
/***** creating choice to use for switch() and declaring variables to use later *****/
char choice;
int length,breadth,area,perimeter;
printf("\t************************************************************\n");
printf("\t*********** Program to calculate Area or Perimeter *********\n");
printf("\t************************************************************\n\n\n");
/**** getting value of length and breadth from user ****/
printf("\tEnter the Length\n");
printf("\t-> ");
scanf("%d",&length);
printf("\n\tEnter the Breadth");
printf("\n\t-> ");
scanf("%d",&breadth);
/**** Asking for Area or Perimeter choice ****/
printf("\n\tEnter a for Area or P for Perimeter\n");
printf("\t-> ");
scanf(" %c",&choice);
printf("\n");
/***** using switch to calculate Area or Perimeter ******/
switch (choice)
{
/**** for Area ****/
case 'A':
case 'a':
area = length * breadth;
printf("\tLength = %d | Breadth = %d | Area = %d\n",length,breadth,area);
break;
/***** for Perimeter *****/
case 'P':
case 'p':
perimeter = 2 * (length + breadth);
printf("\n");
printf("\tYou entered Length = %d | Breadth = %d |
Perimeter = %d\n",length,breadth,perimeter);
break;
/**** if the input is not Valid ****/
default :
printf("\n");
printf("\tInvalid Choice");
printf("\n");
}
/***** pausing the system ****/
getch();
}
我的问题是,如果用户输入无效选项,直到他输入A或P后的正确选择,如何自动循环代码。
还有什么是必须用于清除屏幕clrscr()的声明似乎不起作用。
答案 0 :(得分:3)
char choice; // this must be outside the loop, to use it after the loop
bool valid_choice = true; // suppose the choice is correct
do // this starts a do-while construction: here we will return if we need to repeat thing
{
ask for choice // copy here your code that asks for the user choice
switch (choice)
{
valid cases // here go your "case 'A'" etc., not to copy it from your question
default:
give your warnings // here you give a warning as in your question
valid_choice = false; // we decide that no, the choice was not valid
break;
}
}
while (!valid_choice) // this will return the control to "do" (repeat the whole thing) only if valid_choice is NOT true
// here we come if valid_choice was true
act according to choice