我正在嘗試為 Wordle 撰寫一個幫助程式,它將顯示所有尚未消除的字母和已確認的字母。我已將程式分解為函式,但confirmed_letters()
函式存在問題。
我在全域范圍內宣告了這個陣列:
char* word[NUM_LETTERS];
它的初始化如下:
for (int i = 0; i < NUM_LETTERS; i ) word[i] = new char(char(42));
這是功能:
void confirmed_letters() {
int num_let = 0; // the # of confirmed letters
int temp_num; // holds the position of the confirmed letter
char temp_letter;
std::cout << "\n\nHow many letters have you confirmed?\n" <<
"Enter only the letters whose positions are known. ";
std::cin >> num_let;
std::cin.ignore(1000, '\n');
if (num_let == 0) return;
std::cout << "Enter the integer position of the confirmed letter, " <<
"followed by the letter. Press the enter (return) key between each entry.\n";
for (int i = 0; i < num_let; i ) {
//temp_num = -1; // I don't think this is needed
std::cin >> temp_num;
std::cin.ignore(1000, '\n');
if (temp_num > 5 || temp_num < 1) {
std::cout << "Invalid letter position. Enter an integer between 1 and 5.\n";
i--;
goto end;
}
std::cin >> temp_letter;
std::cin.ignore(1000, '\n');
word[temp_num - 1] = &temp_letter;
end:
display_word();
}
return;
}
display_word()
只是一個顯示單詞的功能。
這是我得到的輸出:
How many letters have you confirmed?
Enter only the letters whose positions are known. 3
Enter the integer position of the confirmed letter, followed by the letter. Press the enter (return) key between each entry.
1
o
o * * * *
2
i
i i * * *
3
e
e e e * *
因此,出于某種原因,每個額外的字母都在修改之前的字母。我不明白這里發生了什么。每次修改其中一個元素的值時word[]
,它應該只修改一個元素,但它正在修改所有元素。想法?
uj5u.com熱心網友回復:
word[temp_num - 1] = &temp_letter;
存盤將在下一次回圈迭代中重用的區域變數的地址,并保存用戶輸入的任何新值。舊值將丟失,因此看起來所有使用的插槽都存盤相同的字母。因為他們這樣做。更糟糕的是,變數在函式結束時超出范圍,將不再有效。這是危險的,因為指標仍然存在,甚至可能給出看起來正確的結果。
解決方案:不要將指向字母的指標存盤在word
. 存盤字母本身。
char word[NUM_LETTERS];
像這樣初始化:
for (int i = 0; i < NUM_LETTERS; i ) word[i] = '*';
// use the character not the code. It's easier to understand the intent of
// * than the number 42 and not all systems will use 42 for *.
并存盤
word[temp_num - 1] = temp_letter;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/461073.html
下一篇:使用jq將特定欄位轉換為陣列