【问题标题】:Cannot execute code after the loop in c++ [closed]在c ++中循环后无法执行代码[关闭]
【发布时间】:2018-05-02 08:26:43
【问题描述】:

我在 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 &lt;= 10
  • 提示:您的循环定义为从i=0 运行到i=10(11 次),但"inside the loop" 只打印了10 次。进行调查可能会让您了解正在发生的事情。

标签: c++ cpprest-sdk


【解决方案1】:

我认为你应该在循环中使用i &lt; 10 而不是i &lt;= 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 &lt; 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;
}

【讨论】:

  • 你怎么知道数组中的元素不超过10
  • @LogicStuff 我在那之后写了关于 DataArray.size() 的文章,但是其中有 10 个,因为有 10 个循环打印,所以我认为它在第 11 次迭代时失败了
  • 我故意将 DataArray.size() 更改为 10,以确保我只需要迭代到 10 个计数,但我不小心将 '=' 添加到 '
猜你喜欢
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多