C++字符数组循环内正常,循环后仅存最后元素问题求助
问题分析与解决:字符数组循环后仅保留最后一次元素
你的问题出在两处,最直接导致所有元素最终一致的是组合字符串的内部循环逻辑错误,同时还有个变量名冲突的潜在bug:
核心错误:错误的内部循环覆盖所有元素
你在外层循环(for (int i = 0; i < NUM_LOC; i++))中,额外写了一个循环for (int i=0; i<NUM_LOC;i++)来组合字符串。这个循环会把locations数组的所有元素都用当前循环生成的形容词和地点覆盖:
- 第一次外层循环生成
GROTESQUE PORT,你把locations[0]/1/2全改成这个值; - 第二次改成
AVERAGE PAGODA,三个元素再次被全部覆盖; - 第三次改成
FIERCE PLAZA,最终所有元素都被替换成最后一次的结果。
次要bug:变量名冲突
外层循环的计数器是i,内部转大写的循环也用了i,这会导致外层循环的i被意外重置。虽然在你的例子里没影响到循环次数,但这种写法极易引发其他奇怪问题。
修正后的代码
删掉多余的内部循环,直接操作当前外层循环对应的locations[i],同时把转大写的循环变量改成j避免冲突:
#include <iostream> #include <fstream> #include <iomanip> #include <cstring> #include <stdlib.h> #include <time.h> #include <ctype.h> using namespace std; const int MAXCHAR = 99; const int CAP = 999; const int NUM_LOC = 3; // 假设你已实现该随机数生成函数 int getRandNum(int max) { return rand() % max; } void getLocations(char adjectiveList[CAP][MAXCHAR], char placeList[CAP][MAXCHAR], int countAdjectives, int countPlaces,char locations[NUM_LOC][MAXCHAR]){ int randAdj = 0, randPlace = 0; for (int i = 0; i < NUM_LOC; i++){ randAdj = getRandNum(countAdjectives); randPlace = getRandNum(countPlaces); // 改用j作为循环变量,避免与外层i冲突 for (int j=0; j<MAXCHAR;j++){ adjectiveList[randAdj][j] = toupper(adjectiveList[randAdj][j]); placeList[randPlace][j] = toupper(placeList[randPlace][j]); } // 直接给当前locations[i]赋值,无需循环所有元素 strcpy(locations[i], adjectiveList[randAdj]); strcat(locations[i], " "); strcat(locations[i], placeList[randPlace]); cout << "locations[" << i << "] contains: " << locations[i] << endl; } cout << endl; cout << "locations[0] contains: " << locations[0] << endl; cout << "locations[1] contains: " << locations[1] << endl; cout << "locations[2] contains: " << locations[2] << endl; } // 测试用主函数 int main() { srand(time(0)); char adjectives[CAP][MAXCHAR] = {"grotesque", "average", "fierce"}; char places[CAP][MAXCHAR] = {"port", "pagoda", "plaza"}; char locations[NUM_LOC][MAXCHAR]; getLocations(adjectives, places, 3, 3, locations); return 0; }
修正后的输出
循环内和循环外的打印结果会保持一致:
locations[0] contains: GROTESQUE PORT locations[1] contains: AVERAGE PAGODA locations[2] contains: FIERCE PLAZA locations[0] contains: GROTESQUE PORT locations[1] contains: AVERAGE PAGODA locations[2] contains: FIERCE PLAZA
内容的提问来源于stack exchange,提问作者Christian
相关产品推荐
相关产品推荐

