So I would like to build a simple program to input data using structures.
My original program looked like this:
#include <stdio.h>
#include <stdlib.h>
struct student {
int num;
char name[20];
};
int main()
{
int size, i;
scanf("%d", &size);
struct student s[size];
for(i=0; i < size; i++){
scanf("%d", &s[i].num);
scanf("%s", &s[i].name);
}
for(i=0; i < size; i++){
printf("no.:%d\n", s[i].num);
printf("name:%s\n", s[i].name);
}
return 0;
}
My test input would be:
2
1 Name1
2 Name2
It was working but only when data was entered correctly. But when I tried to use more strings in my structure it started to get messy. For example something like this won't work:
#include <stdio.h>
#include <stdlib.h>
struct student {
int num;
char name[20];
char gender;
char address[20];
};
int main()
{
int size, i, j;
scanf("%d", &size);
struct student s[size];
for(i=0; i < size; i++){
scanf("%d", &s[i].num);
scanf("%s", s[i].name);
scanf("%s", s[i].gender);
scanf("%s", s[i].address);
}
for(i=0; i < size; i++){
printf("no.:%d\n", s[i].num);
printf("name:%s\n", s[i].name);
printf("gender:%s\n", s[i].gender);
printf("address:%s\n", s[i].address);
}
return 0;
}
I understood that problem must lay in usage of scanf for string input so I tried to use getchar(). I thought something like this might work.
for(i=0; i < size; i++){
int j=0;
while(( s[i].name[j]=getchar()) != ' ');
j++;
s[i].name[j] = '\0';
}
It's not working though. At this point I got confused and I'm not really sure what is doing wrong. I mean I would like to input something like:
1001 Jeff M No.2_road_city
by using structure, but I'm getting confused how exactly it should be done.