Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中带空格的Scanf_C_Input_Struct_Scanf_Space - Fatal编程技术网

C中带空格的Scanf

C中带空格的Scanf,c,input,struct,scanf,space,C,Input,Struct,Scanf,Space,我有这样的结构: struct bye { char b; char y; char e; } 我想用scanf阅读一行,其中包含一个由3个字母组成的单词,但在彼此之间,有相同的未知空格数 例如: “b[n个空格]y[n个空格]e”,然后输入: struct bye word; word.b='b'word.y='y'和word.e='e' 我做了类似的事情,但不起作用: typedef struct bye bye_s; bye_s setInput() {

我有这样的结构:

struct bye {
    char b;
    char y;
    char e;
}
我想用scanf阅读一行,其中包含一个由3个字母组成的单词,但在彼此之间,有相同的未知空格数

例如: “b[n个空格]y[n个空格]e”,然后输入:

struct bye word;
word.b='b'
word.y='y'
word.e='e'

我做了类似的事情,但不起作用:

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

您只需在格式字符串中添加一个空格,即可跳过无限数量的空格:
scanf(“%c%c%c”、&char1、&char2、&char3)

只需使用

if (scanf("%c %c %c", &ret.b, &ret.y, &ret.e) != 3) {
   /* failed */
}
scanf格式中的任何空白表示跳过输入中的任何空白量


永远不要忘记检查
scanf
返回值

当我只使用
''
字符作为空白时,它对我很有用。如果我混入
'\t'
'\n'
中,你的代码就无法处理这些问题——原因很明显,你是在与文本
'
进行比较(可能请参见ctype.h中的
isspace
)。正如下面的答案所述,标准库可能有一种方法可以获得您想要的行为。如果建议的答案对您的问题不起作用,您应该编辑问题以显示您提供的输入,以及您得到的令人惊讶的结果(与您预期的结果相比)。在第二次调用
setInput()
时,此格式会导致问题。建议添加空格:
%c%c”
-->
%c%c”
@chux Good point。如果换行符(或其他ws)没有在其他地方使用,也就是说。