Scanf input for structs, bitfields in C

Viewed 204
#include <stdio.h>

typedef struct{
    unsigned int _1_:7;
    unsigned int _2_:7;
    unsigned int _3_:7;
    unsigned int _4_:7;
    unsigned int _5_:7;
} grades;

// ---other part of code---

grades student;
int main(){
    scanf("%u\n", student._1_)
    // all the others...
    return 0;
}

I don't know the way to do it. I tried to put & in front of student._1_ but it didn't work. If someone could show me how to do it, not only with bitfields but also with normal structs and enums.

4 Answers

Scanning to a temporary variable should help.

unsigned int tmp = 0;
scanf("%u\n", &tmp);
student._1_ = tmp;

BTW The error message should have informed you about the error reason.

Bitfields cannot have their address taken, and therefore you can't use scanf to write directly to them. You need to write to a temporary, then copy the value to the bitfield.

unsigned tmp;
scanf("%u", &tmp);
student._1_ = tmp;

final program I wrote, but now I have a ERROR with j & i variable in person.grades[1]

#include <stdio.h>


float average;
int i;
int j;

typedef struct{
    char* name_and_year[25];
    short grades[6];
} student;

student person;

void average_calculator(student *x){

    for(j = 0; j > 6; j++)
        average = (x->grades[0] + x->grades[1] + x->grades[2] + x->grades[3] + x->grades[4])/5.0;
    if(average >= 50){
        puts("You passed the year congratulations");
        x->grades[5] = 1;}
    else{
        puts("You didn't pass the year");
        x->grades[5] = 0;}
    printf("Your average is %.2f\n",average);
} 

void student_reader(){
    puts("Enter your full name & your year");
    scanf("%24[^\n]", person.name_and_year);
    puts("what were your grades?\n");
    for(i = 0; i > 6; i++)
        scanf("%hi", &(person.grades[i]));
}

int main(){

    student_reader();
    average_calculator(&person);

    return 0;
}

FINAL code for the readers, thx everybody

#include <stdio.h>

float average; short i;

typedef struct{
    char* name_and_year[25];
    short grades[6]; } student;

student person;

void average_calculator(student *x){

    for(i = 0; i < 5; i++){
        average += person.grades[i]/5;
    }
    if(average >= 50){
        puts("You passed the year congratulations");
        x->grades[5] = 1;}
    else{
        puts("You didn't pass the year");
        x->grades[5] = 0;}
    printf("Your average is %.2f\n",average); } 

void student_reader(){
    puts("Enter your full name & your year");
    scanf("%24[^\n]", person.name_and_year);
    puts("what were your grades?\n");
    for(i = 0; i < 5; i++){
        scanf("%hi", &(person.grades[i]));
    } }

int main(){

    student_reader();
    average_calculator(&person);
    return 0; }
Related