The teacher asked to enter “Tom 89”, which is the form of “name space score”
Question code area:
Three consecutive gets (), the second carriage return cannot end gets ()
printf("s1:\n");
z=gets(s1);
printf("s2:\n");
x=gets(s2);
n1=getnum(z); \\getnum gets name length
n2=getnum(x);
int flag0=0;
\ \ If s3 is the same as one of s1 and s2, re-enter s3
while (flag0==0) {
printf("s3:\n");
c=gets(s3);
n3=getnum(c);
if (n3==n1) {
if (! strncmp(s1,s3,n1)) {
printf("wrong s3! \nn");
}
}
else if (n3==n2){
if (! strncmp(s2, s3, n2)) {
printf("wrong s3! \n");
}
}else
flag0=1;
}
All kinds of stupidity in code writing may also be caused by problems elsewhere.
This is all the code, with comments, please predecessors advice ………… T-T.
char s1[10],s2[10],s3[10],*z,*x,*c;
int n1,n2,n3;
int dg1,dg2,dg3;
char d1[10],d2[10],d3[10];
\ \ Length of name before space
int getnum(char *z){
int num;
while (*z) {
if (*z! =' ') {
num++;
}else
break;
}
return num;
};
\ \ The length of the score after finding the space
int digi(char p1[]){
int dnum=0;
int np=strlen(p1);
int flag=0;
for(int i=0; i<np; i++){
if(p1[i]==' '){
flag=1;
}
if (flag==1&&p1[i]! ='\0') {
dnum++;
}
}
return dnum;
}
int main(){
printf("s1:\n");
z=gets(s1);
printf("s2:\n");
x=gets(s2);
n1=getnum(z);
n2=getnum(x);
int flag0=0;
while (flag0==0) {
printf("s3:\n");
c=gets(s3);
n3=getnum(c);
if (n3==n1) {
if (! strncmp(s1,s3,n1)) {
printf("wrong s3! \nn");
}
}
else if (n3==n2){
if (! strncmp(s2, s3, n2)) {
printf("wrong s3! \n");
}
}else
flag0=1;
}
\ \ Converts the fractional string after the space to an integer type (the method is too stupid, please consult a better method)
dg1=digi(s1);
dg2=digi(s2);
dg3=digi(s3);
for (int i=0; i<dg1; i++) {
d1[i]=s1[n1+i];
}
sprintf(s1, "%d",dg1);
for (int i=0; i<dg2; i++) {
d2[i]=s2[n2+i];
}
sprintf(s2, "%d",dg2);
for (int i=0; i<dg3; i++) {
d3[i]=s3[n3+i];
}
sprintf(s3, "%d",dg3);
\ \ Calculate Average Score
double ave=(dg1+dg2+dg3)/3;
printf("%lf",ave);
}
To convert the fraction behind the space, such as 88, into an integer type, my method is to store it in another array (it is very troublesome to find the length of the fraction first, then I think that while(*p++)) can be used), and then sprintf converts the array string into an integer type, if predecessors have a better way to find education ~ ~
In the getnum function after gets(s2)
int getnum(char *z){ int num; while (*z) { if (*z! =' ') { num++; z++; //Your pointer Z did not advance, and entered a dead cycle. }else break; } return num; };
In addition, by converting a string to an integer, sprintf should be able to directly transfer the address of the beginning of the numeric character after the space to perform the conversion.
You should just push the pointer forward, and you can understand it by checking the use of sprintf below.Then, in fact, why should we use gets for this, directly scanf(“%s %d”,s1), and it is over