【问题标题】:Any suggestions to why this loop isn't executing?关于为什么这个循环没有执行的任何建议?
【发布时间】:2016-08-25 18:01:42
【问题描述】:

我写了下面的函数,它在遇到空格之前将租船人分组在一起,并将每个组保存在一个向量中,一旦遇到空格,它应该寻找另一个组并一遍又一遍地做同样的事情!

到目前为止,我的调试表明 if 语句中的 for 循环由于某种原因没有执行。

char const* MathematicaLib::IsThisAnEquation(char const* equation){

    // execute PEMDAS here

    vector <char const*> SeperatedValues;
    char *TempGH = "";

    int temp = 0;
    int SOG = 0; //start of group

    //cout << equation[2] << endl; // used to test whether the funcion is reading the input parameter


    for (int j = 0; j < strlen(equation); j++)
    {           
        if (isspace(equation[j])) {
            //cout << "processing" << endl; // used to confirm that its reading values until a space is encountered
            for (int n = SOG; n < j - 1; n++){ 
                TempGH[temp] = equation[n];
                temp++;
                SOG = j + 1; //skip charecter
                cout << "test"; //this does not print out meaning that the loop dosen't execute
            }

            temp = 0;
            SeperatedValues.push_back(TempGH);  
        }           
    }

    for (unsigned int p = 0; p < SeperatedValues.size(); p++){ // used for debugging only
        cout << SeperatedValues[p] << endl;
        cout << "This should be reading the vector contents" << endl;
    }

    return "";
}// end of IsThisAnEquation

假设我传递给函数的值是“123 1”,同时假设参数的第一个字符绝不是空格。这意味着当检测到空格时,n == 0 AND j-1 == 2(j-1 表示字符组的结尾,而 n = start) 循环应该导致位置 0 到 2 (123) 中的字符被推入向量中,因此 j 不是 == 0 或 -1。

循环不是直接嵌入在第一个 for 循环下而是在 if 语句下,这不应该强制仅在 if 语句中的条件为真时执行吗?而不是遵循嵌入式循环执行的规则?

关于为什么这个循环没有执行的任何建议?

我一遍又一遍地查看代码以发现任何逻辑错误,但到目前为止我找不到任何错误!

【问题讨论】:

  • 变量TempGH 指向一个长度为零的字符串字面量(技术上是一个字符的数组,字符串终止符),表达式TempGH[temp] = equation[n] 会给你未定义的行为:既是因为您试图修改 constant 的字符串字面量,又是因为您可能越界了。如果您在 C++ 中使用字符串,请使用 std::string(然后您可以执行 TempHG += equation[n] 之类的操作)..
  • 对于这种调试couts,最好放一个std::endlcout 很可能实际上已执行,而您只是看不到它,因为该流从未被刷新
  • @Aboudi 我一遍又一遍地查看代码以发现任何逻辑错误,但到目前为止我找不到任何错误! -- 程序员使用一种叫做“调试器”的东西”。很多时候,我们不能只关注逻辑错误并尝试“在我们的头脑中”运行程序,试图记住变量、它们的值等。现在是您学习使用这个有价值的工具的时候了。
  • @Aboudi 关于为什么这个循环没有执行的任何建议? -- 它没有执行,因为for 中的中间条件n &lt; j - 1 计算为false在第一次迭代中。没有其他原因。现在,为什么它是假的? -- 这就是调试的意义所在。
  • @Aboudi 这是未定义的行为,因为您正在更改字符串文字。之前的评论已经指出了这一点:{ char *temp="abc"; temp[0] = 'x';} 运行那一点代码,如果它崩溃了,不要感到惊讶。

标签: c++ for-loop conditional


【解决方案1】:

我的坏if (isspace(equation[j])是万恶之源,这个条件没有得到满足,因为std::cin &gt;&gt; equation没有注册空格,用这个std::getline(std::cin, equation);替换它设法解决了问题,for循环现在执行。

感谢@PaulMcKenzie 和@Joachim Pileborg 指出修改字符串文字的问题。

对不起,我没有提到我正在通过std::cin&gt;&gt; 传递参数!

【讨论】:

  • @FedeWar,谢谢,我认为它可以正常工作,但看起来不是这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多