[英]C++:array functions
如何編寫一個程序,該程序從鍵盤上讀取字符集並將其輸出到控制台。 數據是隨機輸入的,但有選擇地輸出。 控制台上僅顯示唯一字符。 因此,每個字符無論在數組中出現多少次,都應該顯示一次。
例如,如果一個數組
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] << " ";
}
}
我相信您可以使用std :: set <> 。
“ 集是一種關聯容器,用於存儲 集中的 唯一元素 <...> 元素始終遵循特定的嚴格弱排序標准集從低到高排序。 ”
創建一個用false
初始化的大小為128的數組(假設您正在處理ASCII)會更加有效。 每次獲取一個字符時,請檢查其ASCII值,如果該值上的數組為true,則不打印該字符。 之后,將字符值上的數組值更新為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;
}
}
查看您的代碼...
char myArray [500];
為什么是500? 您使用的數量不得超過8。
char num;
令人困惑的命名。 大多數程序員都希望名為num
的變量為數字類型(例如int
或float
)。
while (entered < 8)
考慮用常量替換8
(例如const int kMaxEntered = 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
注釋不正確, // end if
您// end if
。 if
直到else
結束才結束。
您可能需要在else
子句周圍添加花括號,或通過將if
子句的兩行合並為單行myArray[count++] = num;
從括號中刪除花括號myArray[count++] = num;
。
// prints the list of values
cout<<"The final Array Contains:\n";
for (int i = 0; i < count; i++)
{
cout << myArray[i] << " ";
}
每次輸入一個單據,就在打印列表嗎?
不要使用\\n
在文本中cout
,除非您特別想微觀緩沖。 而是使用endl
。 另外,請始終在二進制運算符(例如<<
周圍放置空格,並且不要隨意大寫單詞:
cout << "The final array contains:" << endl;
for (int i = 0; i < count; i++)
cout << myArray[i] << " ";
cout << endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.