我是C新手。我在GWBASIC中經驗豐富。在努力學習,我試圖寫一個程序,將個別字符轉換成字符串到數值爲這樣:將字符串數組字符轉換爲數字
1 2 3 4 5 6 7 8 9
a b c d e f g h i
j k l m n o p q r
s t u v w x y z
例如,對於字符串用戶輸入可以是「狗」, 表示程序然後將字符串B中的[d] [o] [g]存儲爲[4] [6] [7]。 下面的代碼適用於字符串w /最多四個字符,但必須有更多這樣做的有效方法。
int main()
{
char a[0];
char b[0];
scanf("%s",a);
if (a[0] == 'a' || a[0] == 'j' || a[0] == 's') b[0] = '1';
if (a[0] == 'b' || a[0] == 'k' || a[0] == 't') b[0] = '2';
if (a[0] == 'c' || a[0] == 'l' || a[0] == 'u') b[0] = '3';
if (a[0] == 'd' || a[0] == 'm' || a[0] == 'v') b[0] = '4';
if (a[0] == 'e' || a[0] == 'n' || a[0] == 'w') b[0] = '5';
if (a[0] == 'f' || a[0] == 'o' || a[0] == 'x') b[0] = '6';
if (a[0] == 'g' || a[0] == 'p' || a[0] == 'y') b[0] = '7';
if (a[0] == 'h' || a[0] == 'q' || a[0] == 'z') b[0] = '8';
if (a[0] == 'i' || a[0] == 'r') b[0] = '9';
if (a[1] == 'a' || a[1] == 'j' || a[1] == 's') b[1] = '1';
if (a[1] == 'b' || a[1] == 'k' || a[1] == 't') b[1] = '2';
if (a[1] == 'c' || a[1] == 'l' || a[1] == 'u') b[1] = '3';
if (a[1] == 'd' || a[1] == 'm' || a[1] == 'v') b[1] = '4';
if (a[1] == 'e' || a[1] == 'n' || a[1] == 'w') b[1] = '5';
if (a[1] == 'f' || a[1] == 'o' || a[1] == 'x') b[1] = '6';
if (a[1] == 'g' || a[1] == 'p' || a[1] == 'y') b[1] = '7';
if (a[1] == 'h' || a[1] == 'q' || a[1] == 'z') b[1] = '8';
if (a[1] == 'i' || a[1] == 'r') b[1] = '9';
if (a[2] == 'a' || a[2] == 'j' || a[2] == 's') b[2] = '1';
if (a[2] == 'b' || a[2] == 'k' || a[2] == 't') b[2] = '2';
if (a[2] == 'c' || a[2] == 'l' || a[2] == 'u') b[2] = '3';
if (a[2] == 'd' || a[2] == 'm' || a[2] == 'v') b[2] = '4';
if (a[2] == 'e' || a[2] == 'n' || a[2] == 'w') b[2] = '5';
if (a[2] == 'f' || a[2] == 'o' || a[2] == 'x') b[2] = '6';
if (a[2] == 'g' || a[2] == 'p' || a[2] == 'y') b[2] = '7';
if (a[2] == 'h' || a[2] == 'q' || a[2] == 'z') b[2] = '8';
if (a[2] == 'i' || a[2] == 'r') b[2] = '9';
if (a[3] == 'a' || a[3] == 'j' || a[3] == 's') b[3] = '1';
if (a[3] == 'b' || a[3] == 'k' || a[3] == 't') b[3] = '2';
if (a[3] == 'c' || a[3] == 'l' || a[3] == 'u') b[3] = '3';
if (a[3] == 'd' || a[3] == 'm' || a[3] == 'v') b[3] = '4';
if (a[3] == 'e' || a[3] == 'n' || a[3] == 'w') b[3] = '5';
if (a[3] == 'f' || a[3] == 'o' || a[3] == 'x') b[3] = '6';
if (a[3] == 'g' || a[3] == 'p' || a[3] == 'y') b[3] = '7';
if (a[3] == 'h' || a[3] == 'q' || a[3] == 'z') b[3] = '8';
if (a[3] == 'i' || a[3] == 'r') b[3] = '9';
printf("%s\n",b);
return 0;
}
'「d」 - 「a''等於'3'。 –
請注意,在C中'='運算符是賦值,爲了檢查相等性,使用==運算符。你可以這樣if(strA [0] =='a'|| strA [0] =='j'|| strA [0] =='s')strB [0] = 1; ...以及其他情況下的其他情況,爲每個字符檢查一次使用for或while循環,而不是使用遞增值。 – akoso
@rankep:我認爲salicemspiritus希望'strB [0] ='1''而不是'strB [0] = 1'。 – ruakh