C++中循环结束后代码无法执行的问题求助
问题分析与解决方案:循环后代码未执行的原因
你的程序之所以没走到最后的Outside the loop, second output,大概率是循环过程中触发了数组越界,导致程序异常终止了。
咱们来拆解问题:
- 你写的循环条件是
i <= 10,这会让i从0遍历到10,整整11次迭代。但你的DataArray(从JSON解析来的数组)实际长度很可能小于11——当i超过数组的最大有效索引时,DataArray[i]会直接触发未定义行为(或者某些JSON库会抛出异常),程序直接崩掉,自然就跳过后边的代码了。 - 另外你混用了
std::cout和std::wcout,虽然不一定是直接原因,但不同输出流的缓冲行为可能导致输出看起来混乱,建议统一用宽字符输出的std::wcout。
给你几个解决方案:
1. 用数组实际长度控制循环(最稳妥)
永远不要硬编码循环次数,直接用数组的size()方法来确定迭代范围:
auto DataArray = jvalue.at(U("data")).as_array(); std::wcout << L"Outside the loop, first output" << std::endl; // 用size_t类型更适配容器的索引,避免类型不匹配 for (size_t i = 0; i < DataArray.size(); i++) { auto data = DataArray[i]; auto dataObj = data.as_object(); std::wcout << L"inside the loop" << std::endl; } std::wcout << L"Outside the loop, second output" << std::endl;
2. 添加越界检查与异常捕获(增强健壮性)
如果确实需要遍历固定次数,一定要先检查索引是否在有效范围内,同时用try-catch捕获可能的异常,避免程序直接终止:
auto DataArray = jvalue.at(U("data")).as_array(); std::wcout << L"Outside the loop, first output" << std::endl; try { for (int i = 0; i <= 10; i++) { if (i >= DataArray.size()) { std::wcout << L"Index " << i << L" out of bounds, skipping" << std::endl; continue; } auto data = DataArray[i]; auto dataObj = data.as_object(); std::wcout << L"inside the loop" << std::endl; } } catch (const std::exception& e) { std::wcout << L"Exception caught: " << e.what() << std::endl; } std::wcout << L"Outside the loop, second output" << std::endl;
3. 用范围for循环(更简洁)
如果不需要索引,直接用范围for循环遍历数组,完全避免越界问题:
auto DataArray = jvalue.at(U("data")).as_array(); std::wcout << L"Outside the loop, first output" << std::endl; for (const auto& data : DataArray) { auto dataObj = data.as_object(); std::wcout << L"inside the loop" << std::endl; } std::wcout << L"Outside the loop, second output" << std::endl;
内容的提问来源于stack exchange,提问作者noyruto88
相关产品推荐
相关产品推荐

