如何在已知程序中输入字符串执行新功能
如何在已知程序中输入字符串执行新功能 且不影响原功能 而且此字符串不输入也对程序没影响
/* this is a small game that Mike Ce Shi implemented for his dearest
students who attend his C programing lecture. he tried to use
as few contents students dont know yet as possible. so the code
can be improved as students learn more things. he hopes the
students will find fun in both the game and programing, and also
make the game complete when they finish C programing studying.
2017-10-23 Mike Ce Shi
*/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
char n1,n2,n3,n4;//numbers to guess
char i1,i2,i3,i4,ch[100];//numbers user guesses
int a,b,i; //b:number correct a:position correct
int guess = 10,invalid;
srand(time(NULL));//set the seed for random number
//generate 4 different digits
n1 = rand() % 10 + '0';
n2 = rand() % 10 + '0';
if (n2 == n1)
if( n2 == '9')
n2 = '0';
else
n2++;
n3 = rand() % 10 + '0';
while(n3 == n1 || n3 == n2)
n3 = rand() % 10 + '0';
n4 = rand() % 10 + '0';
while(n4 == n1 || n4 == n2 || n4 == n3)
n4 = rand() % 10 + '0';
//n1='9';n2='5';n3='2';n4='7';//testing numbers
//game starts
printf("add game descriptions and instructions here:\n");
for(i=0;i<guess;i++)
{
invalid = 0;
//get number input
do
{
if( invalid == 1)
printf("Input numbers are invalid! They should be NUMBERS!\n");
else if( invalid == 2)
printf("Input numbers are invalid! They should be Different Numbers!\n");
printf("Please guess and type 4 different digits here: \n");
scanf("%c%c%c%c",&i1,&i2,&i3,&i4);
invalid = 0;
//printf("%c%c%c%c",i1,i2,i3,i4); // for debuging
//getchar(); //try to remove enter
clear(); // clear the buffer
//check if the number is valid
if( i1<'0' || i1>'9' ||i2<'0' || i2>'9' ||i3<'0' || i3>'9' ||i4<'0' || i4>'9')
invalid = 1;
if( i1 == i2 || i1 == i3 || i1 == i4 || i2 == i3 || i2 == i4 || i3 == i4)
invalid = 2;
}while(invalid);
//check number & position
a=0,b=0;
if(i1 == n1)
a++;
else if(i1 == n2)
b++;
else if(i1 == n3)
b++;
else if(i1 == n4)
b++;
if(i2 == n2)
a++;
else if(i2 == n1)
b++;
else if(i2 == n3)
b++;
else if(i2 == n4)
b++;
if(i3 == n3)
a++;
else if(i3 == n2)
b++;
else if(i3 == n1)
b++;
else if(i3 == n4)
b++;
if(i4 == n4)
a++;
else if(i4 == n2)
b++;
else if(i4 == n3)
b++;
else if(i4 == n1)
b++;
//result
printf(" %dA%dB\n",a,b);
//game finished
if(a == 4)
break;
}
if(i < guess)
printf("Congratulations!\n");
else
printf("Game Over! The answer is %c%c%c%c!\n",n1,n2,n3,n4);
return 0;
}
void clear()
{
char c;
while ((c = getchar()) != '\n' && c != EOF) { }
}
这是源代码