gpt4 book ai didi

c - 使用各种参数读取用户输入

转载 作者:行者123 更新时间:2023-11-30 14:59:51 26 4
gpt4 key购买 nike

我正在尝试读取将作为命令接收的用户输入,并且将根据输入执行某些方法。例如,输入可以是:

allocate 3
write 3 ABC 10
quit

输入的每个部分都是其各自方法的关键参数。我一直在尝试找出如何使用 scanf()fgets() 来解释输入的变化。

最佳答案

使用fgets()strtok()结合起来,你可以得到这样的结果:

#include <stdio.h>
#include <string.h>

int main(void)
{
char mystring [100];
char *pch;
while( fgets (mystring , 100 , stdin) ) /* break with ^D or ^Z */
{
//puts (mystring);
pch = strtok (mystring," ,.-");
while (pch != NULL)
{
// do someting with pch, check if it's a command or an argument
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
}
return 0;
}

输出:

write 3 ABC 10

write
3
ABC
10

关于c - 使用各种参数读取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42475680/

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