2011-11-27 47 views
0

如何編寫一個程序讀入鍵盤中的一組字符並將它們輸出到控制檯。數據隨機輸入,但有選擇地輸出。只有唯一的字符顯示在控制檯上。因此,無論數組出現多少次,每個字符都應該顯示一次。C++:數組函數

例如,如果一個數組

Char letterArray[ ] = {B,C,C,X,Y,U,U,U}; 

輸出應該是:

B,C,X,Y,U 

這是我迄今所做的......

char myArray [500]; 
int count = 0; 
int entered = 0; 
char num; 

while (entered < 8) 
{ 
    cout << "\nEnter a Character:"; 
    cin >> num; 

    bool duplicate = false; 
    entered++; 

    for (int i = 0; i < 8; i++) 
    { 
     if (myArray[i] == num) 
      duplicate=true; 
    } 

    if (!duplicate) 
    { 
     myArray[count] = num; 
     count++; 
    } // end if 
    else 
     cout << num << " character has already been entered\n\n"; 

    // prints the list of values 
    cout<<"The final Array Contains:\n"; 

    for (int i = 0; i < count; i++) 
    { 
     cout << myArray[i] << " "; 
    } 
} 
+2

問題或疑問是什麼? – Zohaib

+0

角色是否需要按照輸入的順序出現? –

+0

你的代碼似乎做得很好 –

回答

0

我相信你可以使用std::set<>

集是一種關聯容器中存儲的獨特元素 < ...>一組元素總是從低排序,以更高以下具體嚴格弱排序標準設置

0

它創建一個128位數組(假設你正在處理ASCII碼),這個數組將被初始化爲false。每當你得到一個字符時,檢查它的ASCII值,如果數組是真的,你不打印它。之後,將字符值上數組的值更新爲true。喜歡的東西:

bool *seenArray = new bool[128](); 

void onkey(char input) { 
    if(((int)input) < 0) return; 
    if (!seenArray[(int)input]) { 
     myArray[count] = input; 
     count++; 
     seenArray[(int)input] = true; 
    }   
} 
+0

ASCII只定義[0,127)範圍內的值。 –

+0

錯誤:如果存在非ASCII輸入,則「if」行會從數組邊界中進行訪問,並且出現未定義的行爲。通過將'if(int(input)<0)return;'添加到'onkey'的開頭來修復。 –

+0

固定,謝謝... – idanzalz

0

通過您的代碼看...

char myArray [500]; 

爲什麼500?你永遠不要超過8個。

char num; 

令人困惑的命名。大多數程序員會希望名爲num的變量是數字類型(例如intfloat)。

while (entered < 8) 

考慮一個具有恆定(例如const int kMaxEntered = 8;)替換8

cin >> num; 

cin可能是行緩衝的;即在輸入整行之前它什麼都不做。

for (int i = 0; i < 8; i++) 
{ 
    if (myArray[i] == num) 
     duplicate=true; 
} 

您正在訪問未初始化的元素myArray。提示:您的循環大小不應該爲8.

如果發現重複,請考慮使用continue;

if (!duplicate) 
{ 
    myArray[count] = num; 
    count++; 
} // end if 
else 
    cout << num << " character has already been entered\n\n"; 

您的// end if評論有錯誤。 if直到完成else纔會結束。

您可能希望圍繞else子句添加大括號,或通過將其兩條線組合成單行myArray[count++] = num;,從if子句中刪除大括號。

// prints the list of values 
cout<<"The final Array Contains:\n"; 

for (int i = 0; i < count; i++) 
{ 
    cout << myArray[i] << " "; 
} 

您每次單擊輸入時打印列表?

不要在文本中使用\ncout,除非您特意要微操縱緩衝。相反,使用endl。此外,總是在二進制運算符周圍放置空格,如<<,並且不要隨機大寫單詞:

cout << "The final array contains:" << endl; 
for (int i = 0; i < count; i++) 
    cout << myArray[i] << " "; 
cout << endl;