Reputation: 2056
I just started to play C and I bump into this problem. Here's my code:
#include<stdio.h>
#include<conio.h>
struct person {
int i;
char name[100];
};
int main() {
struct person p[2];
clrscr();
for(int i=0;i<2;i++) {
printf("Enter i:\n");
scanf("%d",&p[i].i);
printf("Enter name:\n");
gets(p[i].name);
}
for(int j=0;j<2;j++) {
printf("ID: %d, Name: %c\n", p[j].i,p[j].name);
}
getch();
return 0;
}
Here's a sample ouput:
The problem is, all char members are not being asked for a value.
UPDATE:
btw, I am using Turbo C++ version 3 compiler.
Upvotes: 3
Views: 468
Reputation: 471249
Two things:
%s
.Here's the corrected code:
int main() {
struct person p[2];
for(int i=0;i<2;i++) {
printf("Enter i:\n");
scanf("%d",&p[i].i);
// Flush input buffer
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
printf("Enter name:\n");
gets(p[i].name);
}
for(int j=0;j<2;j++) {
printf("ID: %d, Name: %s\n", p[j].i,p[j].name);
}
getch();
return 0;
}
%c
expects a char
, but you're trying to pass in a string. It's undefined behavior to have mismatching types.
Output:
Enter i:
1
Enter name:
asdf
Enter i:
2
Enter name:
zxcv
ID: 1, Name: asdf
ID: 2, Name: zxcv
Upvotes: 3
Reputation: 13560
You probably need to clear the input buffer after typing in a number (you press return after the number, but you don't read that return)
You can read the input stream until you read a \n
after calling scanf
:
while( ch = getchar() != '\n' && ch != EOF);
Upvotes: 1
Reputation: 12737
You should either use %s
instead. Expression p[j].name
is a pointer to an array of chars, so you can't print it with %c
.
Upvotes: 0
Reputation: 2010
Use sscanf as scanf is deprecated. You can also use sscanf for reading in strings as well, not just numbers. Also, %c is for printing characters.
#include<stdio.h>
#include<conio.h>
struct person {
int i;
char name[100];
};
int main() {
struct person p[2];
clrscr();
for(int i=0;i<2;i++) {
printf("Enter i:\n");
sscanf("%d", &p[i].i);
printf("Enter name:\n");
sscanf("%s", p[i].name);
}
for(int j=0;j<2;j++) {
printf("ID: %d, Name: %s\n", p[j].i,p[j].name);
}
getch();
return 0;
}
Upvotes: 0
Reputation: 363607
You should print a string with %s
; %c
will interpret the pointer as a char
. (Strictly, I believe the result is undefined behavior.)
Upvotes: 4