【发布时间】: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::endl。cout很可能实际上已执行,而您只是看不到它,因为该流从未被刷新 -
@Aboudi 我一遍又一遍地查看代码以发现任何逻辑错误,但到目前为止我找不到任何错误! -- 程序员使用一种叫做“调试器”的东西”。很多时候,我们不能只关注逻辑错误并尝试“在我们的头脑中”运行程序,试图记住变量、它们的值等。现在是您学习使用这个有价值的工具的时候了。
-
@Aboudi 关于为什么这个循环没有执行的任何建议? -- 它没有执行,因为
for中的中间条件n < j - 1计算为false在第一次迭代中。没有其他原因。现在,为什么它是假的? -- 这就是调试的意义所在。 -
@Aboudi 这是未定义的行为,因为您正在更改字符串文字。之前的评论已经指出了这一点:
{ char *temp="abc"; temp[0] = 'x';}运行那一点代码,如果它崩溃了,不要感到惊讶。
标签: c++ for-loop conditional