I am trying to trim string by using function rtrim()
from string header in c++ without using algorithm.
What I did was I examine start and end position by if there is space exist, simply delete it out using isspace()
but when I compile, now i get this error:
invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘const char*’
and here is my Code:
#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;
}
whenever I set parameter such as string s = ( "hello world\t ");
and run cout << rtrim(s) << endl;
seems to be working but it doesn't work as above code. any suggestions?