简体   繁体   English

C 比所需的参数更多 scanf

[英]C more arguments than required scanf

I have a while loop with scanf() that reads in a single char* value:我有一个带有scanf()的 while 循环,它读取单个 char* 值:

char c[9];

while(c != 'q')
{
    scanf("%s", c);
}

c is then compared with multiple one-character strings to determine which operation should be performed.然后将c与多个单字符字符串进行比较,以确定应该执行哪个操作。

This scanf can receive multiple arguments and I need to know when only one argument is provided to the function or if there are multiple arguments, but whenever I type in more than one argument, the while loop is run separately for each argument entered.这个 scanf 可以接收多个参数,我需要知道什么时候只向函数提供了一个参数,或者是否有多个参数,但是每当我输入多个参数时,while 循环就会为输入的每个参数单独运行。


Edit:编辑:

So say I enter something like "abcd", the while loop will process c="a" , c="b" , c="c" , and c="d" , which is fine, but I need to know that I entered 4 non-white-space elements in the last scan.所以说我输入类似“abcd”的东西,while循环将处理c="a"c="b"c="c"c="d" ,这很好,但我需要知道我在上次扫描中输入了 4 个非空白元素。

So the first argument is the command I am going to run which is a letter, followed by between 0 and 3 arguments for that command, which are strings or numbers:所以第一个参数是我要运行的命令,它是一个字母,然后是该命令的 0 到 3 个参数,它们是字符串或数字:

Example:例子:

"a box 1 2"

When the number of arguments are fixed, I just used a boolean value to know that the next x values of c are supposed to be the arguments, but I have one function which can accept 0 or 1 arguments, eg当参数数量固定时,我只是使用一个布尔值来知道 c 的下一个 x 值应该是参数,但是我有一个可以接受 0 或 1 个参数的函数,例如

"b" is acceptable.
"b 25" is acceptable.

b is basically a search function where the optional argument is the query to check against. b基本上是一个搜索函数,其中可选参数是要检查的查询。 If no argument is provided, it lists all items.如果没有提供参数,它会列出所有项目。 So a boolean value won't work in this case because the number of arguments is not fixed.所以布尔值在这种情况下不起作用,因为参数的数量是不固定的。

So I need to know that if I enter:所以我需要知道,如果我输入:

"a 1 2 3"  x=4
"a 1"      x=2
"a"        x=1

Separate IO from scanning/parsing.将 IO 与扫描/解析分开。

char buf[100];
fgets(buf, sizeof buf, stdin);
int count = 0;  // Count of arguments.
char *p = buf;

while (*p) {
  if (!isspace((unsigned char) *p)) {
    count++;
    // Do something, if desired with *p
  }
  else {
    Handle_UnexpectedWhiteSpaceChar();
  }
  if (isspace((unsigned char) *p)) {
    p++;
  }
  else {
    Handle_UnexpectedTwoNonSpaceChar();
  }

This will allow you to type a series of numbers on each line, until you enter q .这将允许您在每行上键入一系列数字,直到您输入q

char line[1024] = "";
int nums[MAXNUMS];
int counter = 0;
while (strcmp(line, "q\n") != 0) {
    fgets(line, sizeof(line), stdin);
    while (counter < MAXNUMS && sscanf("%d", &nums[counter])) {
        counter++;
    }
}

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

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