2014-10-11 142 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