当前位置:网站首页>std::string::find 返回值的坑
std::string::find 返回值的坑
2022-08-05 01:52:00 【王大渣】
先看一个bug:
string str = "csdn";
unsigned int i = str.find("-");
if (i < 0)
{
cout << "Not Found";
}
else
{
cout << "Found";
}bug在于,unsigned int不可能<0,所以这段代码一定都会走到else。常见的正确写法大家都知道:
string str = "csdn";
int i = str.find("-");
if (i < 0)
{
cout << "Not Found";
}
else
{
cout << "Found";
}但实际上string::find的返回值真的是unsigned
string str = "csdn";
auto i = str.find("-");
cout << typeid(i).name() << endl;这里,string::find不存在时,返回的实际上是string::npos,所以标准写法应该是:
string str = "csdn";
if (str.find("-") == string::npos)
{
cout << "Not Found\n";
}
else
{
cout << "Found\n";
}边栏推荐
猜你喜欢

【Word】Word公式导出PDF后出现井号括号#()错误

(十七)51单片机——AD/DA转换

Exercise: Selecting a Structure (1)

Activity Recommendation | Kuaishou StreamLake Brand Launch Conference, witness together on August 10!

Are testing jobs so hard to find?I am 32 this year and I have been unemployed for 2 months. What should an older test engineer do next to support his family?

CNI (Container Network Plugin)

记录谷歌gn编译时碰到的一个错误“I could not find a “.gn“ file ...”

tcp中的三次握手与四次挥手

Leetcode brushing questions - 22. Bracket generation

如何发现一个有价值的 GameFi?
随机推荐
Day Fourteen & Postman
DDOS攻击真的是无解吗?不!
EBS uses virtual columns and hint hints to optimize sql case
手把手基于YOLOv5定制实现FacePose之《YOLO结构解读、YOLO数据格式转换、YOLO过程修改》
"Configuration" is a double-edged sword, it will take you to understand various configuration methods
【七夕如何根据情侣倾听的音乐进行薅羊毛】背景音乐是否会影响情侣对酒的选择
配置类总结
hypervisor相关的知识点
Bit rate vs. resolution, which one is more important?
蓝牙Mesh系统开发四 ble mesh网关节点管理
多线程涉及的其它知识(死锁(等待唤醒机制),内存可见性问题以及定时器)
ORA-00257
Jin Jiu Yin Shi Interview and Job-hopping Season; Are You Ready?
MySQL learning
Utilities 蓝牙Mesh系统开发五 ble mesh设备增加与移除
Xunrui cms website cannot be displayed normally after relocation and server change
测试工作这么难找吗?今年32,失业2个月,大龄测试工程师接下来该拿什么养家?
The difference between a process in user mode and kernel mode [exclusive analysis]
tcp中的三次握手与四次挥手