简体   繁体   中英

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;
}

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!

您可以简单地在格式字符串中放置一个空格,跳过无限数量的空格: scanf("%c %c %c",&char1,&char2,&char3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM