C++ 有没有关于为什么这个循环不是';不执行?
我写了下面的函数,在遇到一个空间之前将租船人分组,并将每个组保存在一个向量中,一旦遇到一个空间,它应该寻找另一个组,并反复做同样的事情 到目前为止,我的调试表明if语句中的for循环由于某种原因没有执行C++ 有没有关于为什么这个循环不是';不执行?,c++,for-loop,conditional,C++,For Loop,Conditional,我写了下面的函数,在遇到一个空间之前将租船人分组,并将每个组保存在一个向量中,一旦遇到一个空间,它应该寻找另一个组,并反复做同样的事情 到目前为止,我的调试表明if语句中的for循环由于某种原因没有执行 char const* MathematicaLib::IsThisAnEquation(char const* equation){ // execute PEMDAS here vector <char const*> SeperatedValues;
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
char const*MathematicaLib::IsThisAnEquation(char const*equation){
//在这里执行彭达斯
向量分离值;
char*TempGH=“”;
内部温度=0;
int SOG=0;//组的开始
//coutMy bad如果(isspace(等式[j])
是万恶之源,那么这个条件就没有得到满足,因为std::cin>>等式不注册空格,用这个std::getline(std::cin,等式)替换它;
解决了这个问题,for循环现在执行
感谢@PaulMcKenzie和@Joachim Pileborg指出了修改字符串文本的问题
抱歉,我没有提到我正在通过std::cin>
!传递参数。变量TempGH
指向长度为零的字符串文字(从技术上讲是一个一个字符的数组,字符串终止符),表达式TempGH[temp]=等式[n]会给你定义不明确的行为:这两种情况都是因为你试图修改一个字符串常量,然后因为你可能是越界。如果你用C++中的字符串工作,那么你就可以使用“<代码> TEMPHG+=方程式[n] < /代码>)..对于这种调试cout
s,最好放一个std::endl
。很可能是cout
实际执行了,而您只是看不到它,因为流从来没有运行过flushed@Aboudi我已经一遍又一遍地检查代码以发现任何逻辑错误,但到目前为止我还没有发现任何错误!——程序员使用了一些很多时候,我们不能仅仅盯着逻辑错误,试图“在头脑中”运行程序试图记住变量、它们的值等等。是时候学习使用这个有价值的工具了。@Aboudi关于为什么这个循环没有执行有什么建议吗?--它没有执行,因为for
中的中间条件n
在第一次迭代时计算为false
。没有其他原因。现在,为什么为false?--这就是调试的目的。@Aboudi这是未定义的行为,因为您正在更改字符串文字。前面的一条注释已经指出了这一点:{char*temp=“abc”;temp[0]='x';}
运行这一小段代码,如果它崩溃了,不要感到惊讶。@FedeWar,谢谢,我以为它正在工作,但看起来不是这样。