2

Works fine except skips first character in string name. Can anyone explain what I am not seeing?

#include "stdio.h"
/*
*BN
*/
int main(void) {
// Disable stdout buffering
//setvbuf(stdout, NULL, _IONBF, 0);

struct data {
  char name[40];
  char street[50];
  char city[30];
  char state[3];
  char zip[6];
  float salary;
};

struct data p = {
scanf("%s %s %s %s %s %f", &p.name, &p.street, &p.city, &p.state, &p.zip, &p.salary)
};

printf(" Name:%s\n Street:%s\n City:%s\n State:%s\n Zipcode:%s\n Salary:%.2f", p.name, p.street, p.city, p.state, p.zip, p.salary);
return 0;
}
demongolem
  • 9,474
  • 36
  • 90
  • 105
rando
  • 23
  • 2
  • 6
    Because that's not how you initialize the structure. [Read more about `scanf`](http://en.cppreference.com/w/c/io/fscanf), pay close attention to what it returns. – Some programmer dude Nov 29 '16 at 16:35
  • the struct initialization is not proper. check: http://stackoverflow.com/questions/330793/how-to-initialize-a-struct-in-accordance-with-c-programming-language-standards – Ehsan Nov 29 '16 at 16:41
  • I agree it is not how structure is initialized in c. But can somebody please explain why structure is getting initialized properly except the first character? – MayurK Nov 29 '16 at 16:49
  • If you wonder what happens, it's that the `scanf` function write to all the members of the structure, and then the structure is *actually* initialized by the value that `scanf` returns. – Some programmer dude Nov 29 '16 at 18:42

2 Answers2

2

Initialize your structure as struct data p; then you do the scanf.

struct data p;
scanf("%s%s%s%s%s%f", &p.name, &p.street, &p.city, &p.state, &p.zip, &p.salary);

You can check some struct stuff here.

raymelfrancisco
  • 828
  • 2
  • 11
  • 21
  • 1
    That did it thanks!, Ill review proper initialization of structs and further scanf understanding. Thanks all! – rando Nov 29 '16 at 16:50
2

Hi you have gone wrong way to initialize your structure

Use this:

#include "stdio.h"
/*
*BN
*/
int main(void) {
    // Disable stdout buffering
    //setvbuf(stdout, NULL, _IONBF, 0);

    struct data {
      char name[40];
      char street[50];
      char city[30];
      char state[3];
      char zip[6];
      float salary;
    };

    struct data p;//Dont Initialize it here!
    printf("Please Enter Name Street City State Zip Salary:");
    scanf("%s %s %s %s %s %f", &p.name, &p.street, &p.city, &p.state, &p.zip, &p.salary);

    printf(" Name:%s\n Street:%s\n City:%s\n State:%s\n Zipcode:%s\n Salary:%.2f\n", p.name, p.street, p.city, p.state, p.zip, p.salary);
    return 0;
}
hmmftg
  • 1,274
  • 1
  • 18
  • 31