2015-09-17 50 views
-3

我有困难扫描从用户输入的整数(且将其存储)后进入一个int仅当!后直接印刷:Ç - 如何只扫描符号

char cmd[MAX_LINE/2 + 1]; 
    if (strcmp(cmd, "history") == 0) 
     history(hist, current); 
    else if (strcmp(cmd, "!!") == 0) 
     execMostRecHist(hist, current-1); 
    else if (strcmp(cmd, "!%d") == 0) 
     num = %d; 
    else 
     {//do stuff} 

我明白这是完全错误的语法为strcmp(),但仅作为我如何收集用户输入的示例。

+1

这是什么意思?num =%d;'? – ameyCU

+0

只需设置为数字,无论用户在输入! – Sean

+1

我不这么认为。 – ameyCU

回答

1

strcmp不知道格式说明,它只是比较两个字符串。 sscanf做你想做的事情:它测试一个字符串是否有一定的格式,并将字符串的部分转换为其他类型。

例如:

int n = 0; 

if (sscanf(cmd, " !%d", &num) == 1) { 
    // Do stuff; num has already been assigned 
} 

格式说明%d告诉sscanf寻找一个有效的十进制整数。感叹号没有特殊含义,只有在有感叹号时才匹配。前面的空间意味着该命令可能具有领先的白色空间。不是说在exclam之后和数字之前可能有空格,并且数字可能是负数。

格式说明符对于scanf系列是特殊的,与“%d format of printf”有关,但不同。在其他字符串中通常没有意义,当然,在代码中找不到引号时也是如此。

1

你不喜欢自己写一个检查器吗?

#include <ctype.h> 
#include <stdio.h> 

int check(const char *code) { 
    if (code == NULL || code[0] != '!') return 0; 
    while(*(++code) != '\0') { 
     if (!isdigit(*code)) return 0; 
    } 
    return 1; 
} 


/* ... */ 

if (check(cmd)) 
    sscanf(cmd + 1, "%d", &num); 
0

使用sscanf()并检查其结果。

char cmd[MAX_LINE/2 + 1]; 
num = 0; // Insure `num` has a known value 
if (strcmp(cmd, "history") == 0) 
    history(hist, current); 
else if (strcmp(cmd, "!!") == 0) 
    execMostRecHist(hist, current-1); 
else if (sscanf(cmd, "!%d", &num) == 1) 
    ; 
else 
    {//do stuff}