Loreto Gabawa Jr.
Loreto Gabawa Jr.

Reputation: 2056

C Struct char members getting a weird values

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:

enter image description here

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

Answers (5)

Mysticial
Mysticial

Reputation: 471249

Two things:

  1. You need to clear the input buffer to keep it from eating the newline.
  2. Secondly, you need to change the format string to %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

Fox32
Fox32

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

Phonon
Phonon

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

Brett McLain
Brett McLain

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

Fred Foo
Fred Foo

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

Related Questions