1
非const引用的无效初始化我想通过使用函数rtrim()
从C++中的字符串头部修剪字符串而不使用算法。 我所做的是我检查开始和结束位置,如果有空间存在,只需使用isspace()
删除它,但是当我编译时,现在我得到此错误: 无效初始化类型为'std :: string & {又名性病:: basic_string的&}”从类型的右值‘为const char *’类型'std :: string&
,这里是我的代码
#include <iostream>
#include <string>
using namespace std;
string rtrim(string& s) {
size_t i;
for(i = s.length() - 1; i != (size_t)-1; i--) {
if(!(isspace(s[i]))){
break;
}
}
return s.substr(0, i + 1);
}
int main(){
cout << "|" << rtrim(" hello world\t ") << "|" << endl;
}
每当我设置的参数,如string s = ( "hello world\t ");
和运行cout << rtrim(s) << endl;
似乎是工作但它不能像上面的代码那样工作。有什么建议么?谢谢。