老师要求输入"Tom 89"这种"姓名空格分数"的形式
问题代码区域:
连续三个gets(),第二个回车无法结束gets()
printf("s1:\n");
z=gets(s1);
printf("s2:\n");
x=gets(s2);
n1=getnum(z); \\getnum得到姓名长度
n2=getnum(x);
int flag0=0;
\\如果s3跟s1、s2其中一个相同,重新输入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;
}
代码写的各种蠢,也可能是其他地方哪里出问题了影响到了这里……
这是全部代码,加了注释,请前辈指点…………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];
\\求空格前姓名的长度
int getnum(char *z){
int num;
while (*z) {
if (*z!=' ') {
num++;
}else
break;
}
return num;
};
\\求空格后分数的长度
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;
}
\\把空格后的分数字符串转换成整数型(方法太笨了,请教更好的方法)
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);
\\求平均分
double ave=(dg1+dg2+dg3)/3;
printf("%lf",ave);
}
把空格后方的分数比如88转换成整数型,我用的方法是存进另一个数组内(要先求分数长度,很麻烦,后来觉得可以用while(*p++)),然后sprintf把数组字符串转换成整数型,如果前辈们有更好的方法求教育~~
In the getnum function after gets(s2)
In addition, when converting a string to an integer, sprintf should be able to directly transmit the address starting from the numeric character after the space for conversion.
You should be able to advance the pointer a little. You can understand it by checking the usage of sprintf below.
Then, why do we need to use gets for this? Just scanf("%s %d",s1) and it’s over
Why do you want this problem to be so complicated?
Your teacher’s requirement is that the format is name, space, score
You can directly analyze the input string. If the string format does not match, the output format does not match. If it matches, register