结构体数组的数据输入错误

img

想试用一下结构体数组,结果开头就出现问题,想输入三个数据却只能输入两个,打印还有错,求告知错误!

供参考:

img

以下答案引用自GPT-3大模型,请合理使用:

。

答:
你的代码可能有以下几个问题:
1. 结构体数组的定义不正确,少了大括号:
   示例:struct student stu[3]; 
2. 数据输入的循环范围不对,少了一个:
   示例:for (i = 0; i < 3; i++)
3. 打印输出的结构体字段写错:
   示例:printf("%s", stu[i].name);

以下是正确的示例代码:
#include <stdio.h>

struct student{
    char name[20];
    int age;
};

int main(){
    struct student stu[3]; // 定义一个结构体数组
    int i;

    for (i = 0; i < 3; i++){ // 数据输入
        printf("Please enter the %dth name: ", i+1);
        scanf("%s", stu[i].name);
        printf("Please enter the %dth age: ", i+1);
        scanf("%d", &stu[i].age);
    }

    for (i = 0; i < 3; i++){ // 输出结构体数组信息
        printf("The %dth name is %s, age is %d\n", i+1, stu[i].name, stu[i].age);
    }

    return 0;
}

如果我的回答解决了您的问题,请采纳我的回答

因为使用%c读取输入的字符时,读取了遗留在缓冲区的换行符,然后又导致后面读取数字发生了错误,所以导致结果发生了错误;

如果以图片中的格式输入数据,可以在每个scanf()后面增加一个while循环,读走每行输入的多余字符,包括结尾的换行符。

参考链接:


修改如下:

#include <stdio.h>

struct stu{
    char letter;
    int num;
};

int main(void){
    
    struct stu a[3];
    
    for(int i=0;i<3;i++){
        scanf("%c",&a[i].letter);
        
        // 读走输入一个字符后的多余字符 ,包括换行符 
        while(getchar()!='\n'){
            continue;
        }
        
        scanf("%d",&a[i].num);
        
            
        // 读走多余字符,这里主要是读走读取数字后遗留在缓冲区的换行符 
        while(getchar()!='\n'){
            continue;
        }
    }
    
    for(int i=0;i<3;i++){
        printf("%c    %d\n",a[i].letter,a[i].num); 
    }
    
    return 0;
}


img