Reputation: 61
So basically my function goes through every character in a string and inserts each character onto another string so it results in the initial string being reversed. I've looked up online but the answers to this problem seem to not work anymore, I'm not sure if it's because they are from 5+ years ago or I'm getting something wrong somewhere. My code goes like this:
long reverse_num(long n){
string new_str = "";
string my_str = to_string(n);
int my_int;
for (unsigned i = 0; i < my_str.size(); ++i){
new_str.insert(0, char my_str[i]);
}
my_int = stol(new_str);
return my_int;
}
The error given is: expected primary-expression before 'char' new_str.insert(0, char my_str[i]);
What am I doing wrong? Thanks!
Upvotes: 1
Views: 454
Reputation: 5871
Your type cast syntax was bad, but you appear to be attempting to insert a char into an std::string. This is the function you appeared to be going for:
http://en.cppreference.com/w/cpp/string/basic_string/insert
basic_string& insert( size_type index, size_type count, CharT ch );
Try
new_str.insert(0, 1, my_str[i]);
You also could have used http://en.cppreference.com/w/cpp/algorithm/reverse
std::reverse(my_str.begin(), my_str.end());
Upvotes: 0
Reputation: 3765
First, you shouldn't specify the char
type in the insert expression. Also, there isn't a string insert function that matches what you're doing here; you probably want one of these:
basic_string& insert(size_type pos, size_type n, charT c);
iterator insert(const_iterator p, charT c);
So your insert line should be one of these:
new_str.insert(0, 1, my_str[i]);
new_str.insert(new_str.begin(), my_str[i]);
Upvotes: 1