简体   繁体   English

获取以逗号分隔的输入 + 获取输入的问题

[英]Get input separated by commas + problem getting input

I'm trying to get the input of a user in the following param1,param2,param3 problem is that I'm not allowed to use scanf.我试图在以下param1,param2,param3中获取用户的输入,问题是我不允许使用 scanf。 I want to retrieve those 3 parameters into 3 different variables but: - I don't know how to get them because they're separated by a comma - I can't manage to use well sscanf and from what I've seen, I don't think fgets can help me.我想将这 3 个参数检索到 3 个不同的变量中,但是: - 我不知道如何获取它们,因为它们用逗号分隔 - 我无法很好地使用 sscanf,从我所见,我不要认为 fgets 可以帮助我。 Ex:前任:

char a1, a2, a3;
printf("Enter data\n");
sscanf(input,"%[^,],%[^,],%[^,]", &a1, &a2, &a3);

I'm not asked to type the arguments that I want.我没有被要求输入我想要的 arguments。 Is there something I'm missing here?我在这里缺少什么吗?

You can use fgets and sscanf like:您可以像使用fgetssscanf一样:

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
}

If you are not allowed to use scanf , I doubt using a variation of it like sscanf will be allowed.如果您不允许使用scanf ,我怀疑是否允许使用它的变体,例如sscanf It seems the point of the exercise is that you learn how to manually parse a string.看来练习的重点是学习如何手动解析字符串。

To do that, you can take several approaches.为此,您可以采取多种方法。 One is reading the entire line in memory and then parsing it.一种是读取 memory 中的整行,然后解析。 Another is going character by character and doing the parsing at the same time as the reading.另一个是逐个字符地进行解析,并在阅读的同时进行解析。

Whatever you do, you have to make a loop and scan for the comma , character (to know when to go to the next argument) and the end line \n one (to stop in the last one), while copying the other characters into each string.无论您做什么,都必须循环并扫描逗号,字符(知道何时将 go 转到下一个参数)和结束行\n一个(在最后一个停止),同时将其他字符复制到每个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM