hello everyone i'm new ic and i have a problem on structs, on the very simple
i want to create a struct with one int and a char table 3 potisions,this is my code

#include <stdio.h>
#include <string.h>
#include <conio.h>
struct domi
{
    int code;
    char name[3];
};
main()
{
    struct domi don;
    int i;
    printf("Dwse times gia ta meloi tis domis ");
    scanf("%d",&(don.code));
    for (i=0;i<3;i++)
    {
    //  don.name[i]=getchar();
        scanf("%c",&(don.name[i]));
    }
    printf("Oi times pou dwsate einai: %d kai ",don.code);

    for (i=0;i<3;i++)
    {
        printf("%c",(don.name[i]));
    }

}

i want to put on my keyboard the values 5 a b c and it should be the output
5
a
b
c
but it didn't any idea?
thanks

Not scanf("%c", &someVariable), but scanf(" %c", &someVariable);

The %c format needs a space before it, to "eat" the newchar char, and get past it.

You've told us what it DOESN'T do. But what DOES it do?

You'll need some newlines in your printf statements if you want things to print on separate lines. As for the main problem (which I assume is that the spaces are not weeded out), a space is a legitimate character, so scanf with a "%c" modifier is going to gobble up that space as a legitimate character and move on. Try entering "5abc" (no spaces) rather than "5 a b c" and see if you get output more to your liking.

To actually fix it, you'll want to think about what valid input is. Presumable white space is not valid input, so it should be read and then immediately discarded. If that's the case, perhaps test for it, adding code right after the scanf statement. You'll need to #include the ctype.h library.

if(isspace(don.name[i]))
{
    i--; // reject white space.  for-loop will increment i, so we subtract here to force a "do-over"
}

thanks for the replies :)
Adak you are correct, the problem was the space before the %
now is work fine....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.