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

标签 c scanf

我有以下代码,我要求用户输入一个字符串“towers”,后跟整数。当我尝试扫描数据输入时,给出以下信息: 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);
}
}

我想要实现的是检查用户输入是单独键入“towers”还是键入“towers”后跟一组其他三个整数。非常感谢您的帮助!

最佳答案

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 */

关于c - C语言如何收集多个格式参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35303280/

相关文章:

c - 检索正在运行的进程的名称

如果符号之间没有空格,C 计数字程序就可以工作,为什么?

c - 在 C 中,我如何从文件中扫描并与另一个扫描进行比较

c - sscanf long hex 数字到 long long int

C程序查找数字序列中缺失的整数

c++ - 不代表正确数量的结构的字节计数。

c - While 循环文本文件意外停止

C scanf 无效输入时被忽略

线性代数的 C 库

c - 为什么 SUCCEEDED 宏中有这么多括号?