gpt4 book ai didi

c - 确定 C 缓冲区中的多个空格分隔的输入

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:51 24 4
gpt4 key购买 nike

在为我的命令解释器读取输入时,我一直在努力证明我的逻辑。我遇到的问题是 strstr() 要么不接受 "%s" 作为,要么正在处理整个 haystack 作为字符串,因此忽略空格、换行符等。

char command[4] = "";
char arg1[512] = "";
char arg2[512] = "";
char tmp[1029] = "";
char buffer[BUFFERSIZE];
memset(buffer, '\0', BUFFERSIZE);

while(fgets(buffer, BUFFERSIZE, stdin) != NULL){
strcpy(command, "");
strcpy(arg1, "");
strcpy(arg2, "");
strcpy(tmp, "");
if(strstr(buffer, "%s\n") != NULL)
sscanf(buffer, "%s", command); // 0 arguments
if(strstr(buffer, "%s %s") != NULL)
sscanf(buffer, "%s", arg1); // 1 argument
if(strstr(buffer, "%s %s %s") != NULL)
sscanf(buffer, "%s", arg2); // 2 arguments
printf("%s %s %s\n", command, arg1, arg2);
}

无论我输入什么:

  • com
  • val argument1val
  • 命令 arg1 arg2val
  • 等等

对于 commandarg1arg2,我总是以空字符数组结束。

我的输入将始终是单个字符串或最多三个空格分隔的字符串,后跟一个换行符。

最佳答案

您只需扫描一次并检查 sccanf 返回的已解析参数的数量(特别检查输入的空行)

#include <stdio.h>
#include <strings.h>

#define BUFFERSIZE 2000

int main()
{
int nb_args;
char command[4] = "";
char arg1[512] = "";
char arg2[512] = "";
char buffer[BUFFERSIZE];
memset(buffer, '\0', BUFFERSIZE);

while(fgets(buffer, BUFFERSIZE, stdin) != NULL){
strcpy(command, "");
strcpy(arg1, "");
strcpy(arg2, "");

nb_args = sscanf(buffer, "%3s%511s%511s", command,arg1,arg2);
if (strlen(command)==0)
{
printf("empty line\n");
}
else
{
switch(nb_args)
{
case 1:
printf("Command = %s\n",command);
break;
case 2:
printf("Command = %s, arg1 = %s\n",command,arg1);
break;
case 3:
printf("Command = %s, arg1 = %s, arg2 = %s\n",command,arg1,arg2);
break;
}
}
}
}

关于c - 确定 C 缓冲区中的多个空格分隔的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39821122/

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