C++ std::string::find 总是返回 npos
C++ std::string::find always returns npos?
我试图让这个函数切开一个字符串,然后返回它,没有空格和全部小写。为此,我试图找到一个" "
,以查看字符串"The Time Traveller (for so it will be convenient to speak of him)"
是否包含空格。
代码如下,将上面的字符串传递给此函数。它总是返回string::npos
.对这个问题有任何想法吗?
string chopstring(string tocut){
string totoken = "";
int start = 0;
while(tocut[0] == ' ' || tocut[0] == 10 || tocut[0 == 13]){
tocut.erase(0);
}
int finish = 0;
finish = tocut.find(" ", start);
if (finish == string::npos){
cout << "NPOS!" << endl;
}
for (int i = start; i < finish; i++){
totoken += tocut[i];
}
tocut.erase(start, finish);
return tokenize(totoken);
}
>tocut.erase(0)
正在擦除所有tocut
。参数是要擦除的第一个字符,默认长度为"所有内容"。
tocut[0 == 13]
可能应该tocut[0] == 13
.这些说法大相径庭。另外,请与字符值('t'
(而不是整数进行比较。顺便说一下,结合前面的是你的实际问题:tocut[0 == 13]
变得tocut[false]
,这是tocut[0]
,这是true
。所以循环一直运行到tocut
为空,这是立即的(因为你在第一次去中过度地擦除了它(。
上述两个 bug 的净效果是,当你到达 find
语句时,tocut
是空字符串,它不包含空格字符。继续前进...
您可以使用 substr
函数而不是循环从 tocut
迁移到 totoken
。
您的最后一行tocut.erase(start, finish)
没有做任何有用的事情,因为tocut
是按值传递的,之后您会立即返回。
实际上,大多数代码可以写得更简单(假设我理解您要删除所有空格是正确的(:
string chopstring(string tocut) {
std::string::size_type first(tocut.find_first_of(" nr"));
if (first != tocut.npos) {
tocut.substr(first);
}
tocut.erase(std::remove(tocut.begin(), tocut.end(), ' '), tocut.end());
return tokenize(tocut);
}
如果您实际上要删除所有空格,则可能需要将std::remove_if()
与合适的谓词一起使用。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- std::string::find 总是返回 string::npos 偶数
- 为什么s.find在失败时返回字符串::npos而不是s.length()
- C++ std::string::find 总是返回 npos
- 简单的问题:为什么字符串库函数std::string::find总是返回std::string::npos