while 判断条件返回值和判断条件赋值的问题。

astmd 2009-03-02 04:54:02
程序如下:
#include <iostream>
#include <string>
int main()
{
using namespace std;
const string str( "ab2c3d7R4E6" );
string::size_type sz1 = 0, sz2 = 0;
// 这里出现问题。
while ( ( sz2 = str.find_first_not_of( "0123456789", sz2 )) != string::npos ) {
cout << "sz2 = " << sz2 << endl;
cout << "found character at index: " << sz2
<< " element is " << str[sz2] << endl;
++sz2;
}
cout << "Done.\n";
return 0;
}
问题出现:
while判断条件( sz2 = str.find_first_not_of( "0123456789", sz2 )) != string::npos 和 ( sz2 = str.find_first_not_of( "0123456789", sz2 )) && sz2 != string::npos 有什么不同?
我在google里面没有搜到答案。麻烦各位兄弟帮我解释一下。谢谢啦!
...全文
322 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
bfhtian 2009-03-02
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 astmd 的回复:]
没发完,抱歉!
现在恍然大悟!!
谢谢大家!
[/Quote]
可以结贴了
ctan 2009-03-02
  • 打赏
  • 举报
回复
[Quote=引用楼主 astmd 的帖子:]
( sz2 = str.find_first_not_of( "0123456789", sz2 )) != string::npos 和 ( sz2 = str.find_first_not_of( "0123456789", sz2 )) && sz2 != string::npos 有什么不同?
[/Quote]

while ( ( sz2 = str.find_first_not_of( "0123456789", sz2 )) != string::npos )
{
}
相当于
sz2 = str.find_first_not_of( "0123456789", sz2 );
while (sz2 != string::npos )
{
}


while (( sz2 = str.find_first_not_of( "0123456789", sz2 )) && sz2 != string::npos )
{
}
则相当于
sz2 = str.find_first_not_of( "0123456789", sz2 );
while (sz2 && (sz2 != string::npos ))
{
}
看出两者的区别了吧?
后者多出了一个条件
astmd 2009-03-02
  • 打赏
  • 举报
回复
没发完,抱歉!
现在恍然大悟!!
谢谢大家!
astmd 2009-03-02
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 hai040 的回复:]
( sz2 = str.find_first_not_of( "0123456789", sz2 )) && sz2 != string::npos
str.find_first_not_of返回第一个(0)时判断式是false
[/Quote]
您说的非常对! 问题就出在这里了,我没弄明白为什么!
astmd 2009-03-02
  • 打赏
  • 举报
回复
谢谢您的回复,不过我没看明白。您能再解释的细一些吗?谢谢您!
hai040 2009-03-02
  • 打赏
  • 举报
回复
( sz2 = str.find_first_not_of( "0123456789", sz2 )) && sz2 != string::npos
str.find_first_not_of返回第一个(0)时判断式是false
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ssm1984119 的回复:]
问题应该出在变量上,sz2 = str.find_first_not_of( "0123456789", sz2 ),最好改成
szFind = str.find_first_not_of( "0123456789", sz2 ))
[/Quote]
同意,不要让实参又接收返回变量,这样容易出错.
ssm1984119 2009-03-02
  • 打赏
  • 举报
回复
问题应该出在变量上,sz2 = str.find_first_not_of( "0123456789", sz2 ),最好改成
szFind = str.find_first_not_of( "0123456789", sz2 ))

64,639

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧