简体   繁体   English

Scanf在C中有空格

[英]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. 我想用scanf读一行包含3个字母但在彼此之间的字,有相同的未知空间数。

For example: "b[n number of space]y[n number of space]e" and then put in: 例如:“b [n个空格] y [n个空格数] e”然后放入:

struct bye word;

word.b = 'b' word.y = 'y' and word.e = 'e' word.b = 'b' word.y = 'y'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. scanf格式的任何空白区域都意味着跳过输入中的任何数量的空白区域。

And never forget to check the scanf return value! 永远不要忘记检查scanf返回值!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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