[英]Get input separated by commas + problem getting input
我试图在以下param1,param2,param3
中获取用户的输入,问题是我不允许使用 scanf。 我想将这 3 个参数检索到 3 个不同的变量中,但是: - 我不知道如何获取它们,因为它们用逗号分隔 - 我无法很好地使用 sscanf,从我所见,我不要认为 fgets 可以帮助我。 前任:
char a1, a2, a3;
printf("Enter data\n");
sscanf(input,"%[^,],%[^,],%[^,]", &a1, &a2, &a3);
我没有被要求输入我想要的 arguments。 我在这里缺少什么吗?
您可以像使用fgets
和sscanf
一样:
char input[10];
char a1, a2, a3;
if (fgets(input, sizeof input, stdin))
{
if (sscanf(input, "%c,%c,%c", &a1, &a2, &a3) == 3)
{
// ok - go on and use a1, a2, a3
}
else
{
// not good, the input doesn't match the pattern
}
}
else
{
// not good, didn't get any input
}
如果您不允许使用scanf
,我怀疑是否允许使用它的变体,例如sscanf
。 看来练习的重点是学习如何手动解析字符串。
为此,您可以采取多种方法。 一种是读取 memory 中的整行,然后解析。 另一个是逐个字符地进行解析,并在阅读的同时进行解析。
无论您做什么,都必须循环并扫描逗号,
字符(知道何时将 go 转到下一个参数)和结束行\n
一个(在最后一个停止),同时将其他字符复制到每个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.