如何用C语言收集多个格式参数?

时间:2016-02-09 22:16:11

标签: c scanf

我有以下代码,我要求用户输入字符串'towers'后跟整数。当我尝试scanf数据输入时,给出以下内容: enter image description here

这是代码:

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

int main(int argc, char **argv)

{
int n, from, dest;
char code[]= "towers";


printf ("Code?");
scanf ("%c ", &code);

printf ("Code?");
scanf ("%d %d %d", &n, &from, &dest);


if (strcmp(code,"towers")==0 && n==0){
n=3;
from = 1;
dest = 2;
    if (argc > 1){ 
        n = atoi(argv[1]);
    }
    towers(n, from, dest);
    exit(0);
}
else{
printf ("nothing\n");
printf ("%d",n);
}
}

我想要实现的是检查用户输入是否只是单独输入'塔'或者输入'塔'后跟一组其他三个整数。非常感谢你的帮助!

1 个答案:

答案 0 :(得分:4)

char line[80];
int a, b, c;
fgets(line, 80, stdin);

if (sscanf(line, "towers %d%d%d", &a, &b, &c) == 3)
    /* read in towers and three ints */
else if (strcmp(line, "towers") == 0)
    /* read in towers */