首页 > 解决方案 > 在c ++中循环后无法执行代码

问题描述

我在 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.

请帮忙。谢谢你。

标签: c++cpprest-sdk

解决方案


我认为你应该i < 10i <= 10你的循环中使用:

for (int i = 0; i < 10; i++)
{
    auto data = DataArray[i];
    auto dataObj = data.as_object();

    std::wcout << "inside the loop" << std::endl;
}

您的最后一次迭代没有在循环内输出。它在那里失败,没有DataArray[10]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;
}

推荐阅读