gpt4 book ai didi

c - 如何 sscanf 以确保缓冲区正是我想要的?

转载 作者:太空狗 更新时间:2023-10-29 16:56:39 24 4
gpt4 key购买 nike

我想 sscanf 一行并确保其中没有我想要的内容。代码如下所示:

void parse_init_command(char *buffer, command *new_command) {
if (sscanf(buffer,
"%s %d %d %d %d %d %d %d\n",
new_command->name,
&new_command->data[0],
&new_command->data[1],
&new_command->data[2],
&new_command->data[3],
&new_command->data[4],
&new_command->data[5],
&new_command->data[6]) != 8) {
strncpy(new_command->name, "WRONG_INPUT", 15);
}
}

当我得到这样的输入时:

INIT 9 11 3 1 1 1 9

一切都很好,但是像这样的输入

INIT 9 11 3 1 1 1 9 s

也被接受。我认为如果我添加“\n”一切都会正常工作,因为我知道每个输入行都以 EOL 结尾,但事实并非如此。

最佳答案

如果您的输入总是在末尾有一个换行符,那么这样的事情就可以做到。该代码需要一个额外的 char 类型并检查它是否为 \n,以及正确的扫描项目数。它打印 1 表示成功 - 为本示例的目的对您的函数稍作改动。

#include <stdio.h>

typedef struct {
char name[100];
int data[7];
} command;

int parse_init_command(char *buffer, command *new_command) {
char eol = 0;
int num = sscanf(buffer, "%s%d%d%d%d%d%d%d%c",
new_command->name,
&new_command->data[0],
&new_command->data[1],
&new_command->data[2],
&new_command->data[3],
&new_command->data[4],
&new_command->data[5],
&new_command->data[6],
&eol);
return num == 9 && eol == '\n';
}

int main(void)
{
char inp[50];
command rec;
fgets(inp, sizeof inp, stdin);
printf("%d\n", parse_init_command(inp, &rec) );
return 0;
}

从键盘编程 session :

INIT 9 11 3 1 1 1 9
1

INIT 9 11 3 1 1 1 9 s
0

注意 %c 之前没有前导空格,这会导致空格被跳过,从而破坏了拥有它的意义。

关于c - 如何 sscanf 以确保缓冲区正是我想要的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37102515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com