invalid initialization of non-const reference of type ‘std::string& -
i trying trim string using function rtrim()
string header in c++ without using algorithm. did examine start , end position if there space exist, delete out using isspace()
when compile, error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ rvalue of type ‘const char*’
and here code
#include <iostream> #include <string> using namespace std; string rtrim(string& s) { size_t i; for(i = s.length() - 1; != (size_t)-1; i--) { if(!(isspace(s[i]))){ break; } } return s.substr(0, + 1); } int main(){ cout << "|" << rtrim(" hello world\t ") << "|" << endl; }
whenever set parameter such string s = ( "hello world\t ");
, run cout << rtrim(s) << endl;
seems working doesn't work above code. suggestions? thank you.
the above code create temporary object of std::string
on stack , pass function non-const reference. dangerous function modify object (which doesn't make sense) or remember reference object , try modifying out of scope once object destroyed.
in function don't require non-const
reference, change parameter const std::string &s
, work.
Comments
Post a Comment