ورود

View Full Version : تبدیل دستور getche(); به scanf



MrasoolF
دوشنبه 02 بهمن 1391, 20:54 عصر
سلام دوستان تو یه برنامه میخواستم کتابخونه conio رو ننویسم مجبورم یه جا دستور getche(); رو به scanf تبدیل کنم. دقت کنید که دستور getche(); هست نه getch(); ممنون

omidshaman
دوشنبه 02 بهمن 1391, 20:59 عصر
کدتو کامل بزار

MrasoolF
دوشنبه 02 بهمن 1391, 21:17 عصر
#include <stdio.h>
#include <conio.h>

//Tabe Tashkhise Adad.
int isNum(char Chr)
{
if ( '0' <= Chr && Chr <= '9' ) return 1;
return 0;
}

//Tabe Tashkhise Amalgar.
int isOp ( char Chr )
{
if ( Chr == '+' || Chr == '-' || Chr == '*' || Chr == '/' || Chr == '^' ) return 1;
return 0;
}

int isSing( char Chr )
{
if ( Chr == '+' || Chr == '-' || Chr == '.') return 1;
return 0;
}

float power(float a, int b){
float pow=1;
for(int i=0; i<b; i++)
pow *= a;
return(pow);
}


//Tabe Mohasebe.
float calcIt( float Num1 , char Op , float Num2 )
{
float Result = 0;
switch (Op)
{
case '+':
Result = Num1 + Num2;
break;
case '-':
Result = Num1 - Num2;
break;
case '*':
Result = Num1 * Num2;
break;
case '/':
Result = Num1 / Num2;
break;
case '^':
Result = power(Num1,Num2);
break;
default:
//Agar Operator Eshtebah bood.
printf("Wrong Parameter!!!");
Result = 0;
break;
}
return Result;

}

int main()
{
printf("Enter the input to calculate (Escape to exit)\n\n");
while(1){

float
Num1 = 0 ,
Num2 = 0 ,
Result = 0 ;

int
IntResult = 0 ,
OpIndex = 0 ,
Index = 0 ,
IsOp = 0 ;


char
Op = ' ' ,
InputCh = '0' ,
CNum1 [10] = {0,0,0,0,0,0,0,0,0,0} ,
CNum2 [10] = {0,0,0,0,0,0,0,0,0,0} ;

do
{
InputCh = getche();
//scanf("%c", &InputCh);
//Check kardane Voroodi.
if( !isNum(InputCh) && !isOp(InputCh) && !isSing(InputCh) && InputCh != '\r' )
{
printf("\nWRONG PARAMETER!!!\n");
return 0;
}

//Tashkhise Operator
if ( isNum(InputCh) && (IsOp == 0)) IsOp = 1;

if (IsOp == 1 && isOp(InputCh))
{
IsOp = -1 ;
Op = InputCh;
Index = 0 ;
OpIndex ++ ;

continue;
}
//Zakhire Adad
if (InputCh != '\r' && (isNum(InputCh) || isSing(InputCh)))
{
if (OpIndex == 0)
CNum1[Index] = InputCh;
else
CNum2[Index] = InputCh;
Index ++;
}
} while(InputCh != '\r');

//Tabdile Reshte Be Adad.

sscanf ( CNum1 , "%f" , &Num1);
sscanf ( CNum2 , "%f" , &Num2);

//Check kardane Operator.
if (Op == ' ')
{
printf("\nWARNING: Oprator Missing!!!\n");
printf("%f\n" , Num1);
return 0;
}
//Mohasebe kardan
Result = calcIt(Num1 , Op , Num2);

if ( (Result - (int)Result) == 0 )
{
//Chape natije (Agar Natije Adade Sahih bud)
IntResult = Result ;
printf ("\nResult = %d\n" , IntResult);
}
else
{
//Chape Natije (Agar Adade Sahih nabud)
printf ("\nResult = %f\n" , Result);
}

//Chape Ravande Hesab kardane Natije
//printf( "\nOp1 = %f \nOprator = %c \nOp2 = %f \nResult = %f \n" , Num1 , Op , Num2 , Result);

char ch;
printf("\nPress <Enter> to continue or <Escape> to exit.\n\n");
scanf("%c", &ch);
if(ch==13)
printf("Enter the new input to calculate:\n\n");
main();
if(ch==27)
break;
}
return 0;
}


دقیقاً همونجایی که متغییر InputCh مقدار دهی میشه