2014-10-11 88 views
0

如何从包含字符和数字的输入字符串中使用scanf读取数字&字符? 例如,如果输入是Fox 2 5我得到F,2,5,如果它是Box 11 21,我得到B,11,21,我试过用scanf(“%cox%d%d “,& s,& t,& u)但它没有工作。 我也试过scanf(“%[^ \ n] s”,& c)并使用(char)c [0],c [4],c [6];但没有成功。从用户读取输入

编辑 - 我原来的方法是正确的,我曾在开发的C++,当我在代码块运行它,它跑了就好

+0

你在哪里找到“%舵手”?字符串是“%s” – JohnKiller 2014-10-11 09:17:35

+0

好吧,如果您在** scanf(“b%db”,&a)** a = 9中输入b9b。这对字符也是如此 – 2014-10-11 09:27:21

回答

1

比方说,你有输入下列格式的毛刺:

串号数字\ n

#include "stdio.h" 

int main() 
{ 
    char string[100]; 
    int a, b; 
    scanf("%99s %d %d",string , &a, &b); 
    printf("The string is:\t%s\n",string); 
    printf("The first int is:\t%d\n",a); 
    printf("The second int is:\t%d\n",b); 
    return 0; 
} 

如果您希望数字为浮点数,则应将%d更改为%f。 另请注意,我假定字符串的最大大小为100个字符(将其更改为任何您认为合乎逻辑的内容)。

如果你只是想读的第一个字符,而忽略字符串中的休息,你可以这样做:

#include "stdio.h" 

int main() 
{ 
    char character; 
    int a, b; 
    scanf("%c%*s %d %d",&character , &a, &b); 
    printf("The string is:\t%s\n",character); 
    printf("The first int is:\t%d\n",a); 
    printf("The second int is:\t%d\n",b); 
    return 0; 
} 
+1

建议检查'scanf()'的结果。 – chux 2014-10-12 05:21:05