-2

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.

noyruto88
  • 767
  • 2
  • 18
  • 40
  • 3
    Are you sure about `i <= 10`? – LogicStuff May 02 '18 at 08:29
  • hint: your loop is defined to run from `i=0` to `i=10` (11 times), but `"inside the loop"` is printed only 10 times. Investigating that may give you an idea of what's happening. – Zinki May 02 '18 at 08:31

1 Answers1

1

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;
}
Alexey Usachov
  • 1,364
  • 2
  • 8
  • 15
  • 2
    How do you know there's no more than `10` elements in the array? – LogicStuff May 02 '18 at 08:31
  • 1
    @LogicStuff I wrote about DataArray.size(), after that, but there are 10 of them because there are 10 prints from loops, so it fails on 11th iteration, I think – Alexey Usachov May 02 '18 at 08:33
  • I purposely change DataArray.size() to 10 just to insure that i have to iterate to 10 counts only, but i accidentally add '=' to '<'. My bad. T.Y. – noyruto88 May 02 '18 at 08:52