Search code examples
c++cpprest-sdk

Cannot execute code after the loop in c++


I'm facing a problem in c++ that I don't understand.

this is my code:

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;

Output:

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

It seems the code stops after the loop reach its end. But why?

But if I commented out the

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

it doesn't have a problem.

By the way I'm working on cpprest and get json object data from api. The jvalue variable holds the result.

And if I try and catch the code:

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;
}

the result is infinite loop with output: not an object.

Please help. Thank you.


Solution

  • I think you should use i < 10 instead i <= 10 in your loop:

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

    Your last iteration hasn't output inside the loop. It fails there, there is no DataArray[10] with 10 index

    And much better is to use DataArray.size() instead 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;
    }