ilacollie
ilacollie

Reputation: 57

Scanf with space in C

I have this structure:

struct bye {
    char b;
    char y;
    char e;
}

and I want to read with scanf a line that contains a word of 3 letters but between each other, there is the same unknown number of space.

For example: "b[n number of space]y[n number of space]e" and then put in:

struct bye word;

word.b = 'b' word.y = 'y' and word.e = 'e'

I did something like this but it doesn't work:

typedef struct bye bye_s; 

bye_s setInput() {
    bye_s ret;
    char current_char;

    scanf("%c", &current_char);
    ret.b = current_char;

    do {
        scanf("%c", &current_char);
    } while (current_char == ' ');
    ret.y = current_char;

    do {
        scanf("%c", &current_char);
    } while (current_char == ' ');
    ret.e = current_char;

    return ret;
}

Upvotes: 3

Views: 104

Answers (2)

Jens
Jens

Reputation: 72697

Just use

if (scanf("%c %c %c", &ret.b, &ret.y, &ret.e) != 3) {
   /* failed */
}

Any white-space in a scanf format means to skip any amount of white space in the input.

And never forget to check the scanf return value!

Upvotes: 4

Aganju
Aganju

Reputation: 6405

You can simply put a single space in the format string, that skips an unlimited number of blank space: scanf("%c %c %c",&char1,&char2,&char3);

Upvotes: 1

Related Questions