无法在 c++ 中循环后执行代码

Cannot execute code after the loop in c++

本文关键字:执行 代码 循环 c++      更新时间:2023-10-16

我在 c++ 中遇到了一个我不明白的问题。

这是我的代码:

auto DataArray = jvalue.at(U("data")).as_array();
std::cout << "Outside the loop, first output" << std::endl;
for (int i = 0; i <= 10; i++)
{
auto data = DataArray[i];
auto dataObj = data.as_object();
std::wcout << "inside the loop" << std::endl;
}
std::cout << "Outside the loop, second output" << std::endl;

输出:

Outside the loop, first output
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
inside the loop
Press any key to continue . . .

似乎代码在循环结束时停止。 但是为什么?

但是如果我注释掉

//auto data = DataArray[i];
//auto dataObj = data.as_object();

它没有问题。

顺便说一下,我正在处理 cpprest 并从 API 获取 json 对象数据。jvalue变量保存结果。

如果我尝试捕获代码:

try {
auto data = DataArray[i];
auto dataObj = data.as_object();
std::wcout << "inside the loop" << std::endl;
}
catch (const std::exception& e) {
std::wcout << e.what() << std::endl;
}

结果是无限循环,输出:not an object

请帮忙。谢谢。

我认为你应该使用i < 10而不是在你的循环中i <= 10

for (int i = 0; i < 10; i++)
{
auto data = DataArray[i];
auto dataObj = data.as_object();
std::wcout << "inside the loop" << std::endl;
}

上次迭代未在循环内输出。它在那里失败,没有 10 个索引的DataArray[10]

更好的是使用DataArray.size()而不是i < 10

for (int i = 0; i < DataArray.size(); i++)
{
auto data = DataArray[i];
auto dataObj = data.as_object();
std::wcout << "inside the loop" << std::endl;
}