2017-03-09 63 views
-4

所以我想創建一個儘可能短的功能,將:添加到數組索引根據用戶輸入的每個字母

  1. 獲取用戶輸入的字符串,並把它變成爲const char數組。
  2. 對於整個const char數組,使用for循環來獲取當前索引在for循環中的字母位置。
  3. 然後使用字母順序作爲索引,並在一個由26個整數組成的數組中添加一個索引。

簡而言之:它記錄字符串中字符的頻率並將其添加到整數數組中,因此如果輸入「ABC」,它將輸出1,1,1,0,0等,或者如果我輸入「XXYZZ」它將輸出... 0,0,0,2,1,2。

我已經在這個,但它似乎並沒有工作;

void addCommonToArray(int alphabet_common[], string userinput) { 

const char * alphabet = userinput.c_str(); // String to array 
int index; 

for (int i = 1; i == sizeof(alphabet); i++) { 
    index = alphabet[i] - 64; // Get current index and minus 64 from ascii code to get alphabetical order 
    alphabet_common[index]++; // Add one to the position of the current index in the alphabet 
} } 

我曾經使用過此多次修訂,但未能似乎是一個問題,但在alphabet_common陣列是空白。 (也在main.cpp有一個26整數的數組,但陣列的所有元素都是0)所以這裏的問題是數組停留在0.

我感謝任何幫助!

+1

sizeof(alphabet)會給你什麼?你不應該通過userinput.length()循環,爲什麼我== sizeof(字母)? – Nik

+0

@Nik這是for循環知道在哪裏停止,在這種情況下,一旦我等於數組的大小。 sizeof(字母)給了我有多少元素在數組中。 – Alaanor

+1

你會不會進入for循環? sizeof(字母)會給你什麼? – Nik

回答

0

我固定它,

void addCommonToArray(int alphabet_common[], string userinput) { 
int index; 
for (char& c : userinput) { 
    index = toupper(c) - 64; 
    alphabet_common[index]++; 
} } 

顯然for循環甚至沒有執行,但上述似乎工作。

+0

這裏你的目的是什麼?你怎麼能在這裏問這樣的問題? – Nik

+0

精心製作?初學者在這裏不受歡迎嗎?哦,恥辱。 – Alaanor

+0

歡迎新手入住。 – Nik

相關問題