提问者:小点点

使用string.find()的值在while循环条件中更改


int main()
{
   int pos;
   string str = "asd\t123";
   pos = str.find('\t');
   cout << pos <<endl;
   while (pos =str.find('\t') != string::npos) {
      cout << pos <<endl;
      break;
   }
   cout << pos <<endl;
   return 0;   
}

输出为3和1。 如果我把pos=str.find()放在while循环条件中,为什么会发生这种情况呢?


共1个答案

匿名用户

请尝试以下操作:

while ( (pos = str.find('\t')) != string::npos)
{
...
}

该值已更改,因为while(pos=str.find('\t')!=string::npos)被解释为:

while (pos = (str.find('\t') != string::npos))

您正在将(str.find('\t')!=string::npos)的结果分配给pos,该结果为true。 由于posint,因此true将转换为1

正如注释中提到的,您应该打开您的墙壁警告标志,-wall-wextra-wpedantic,您将立即得到一个警告。 请在此尝试:https://coliru.staked-crooked.com/A/67c5d326f70b9bc1