Reputation: 49
I tried making a small program using the libraries "iostream" and "String" to display a given string backwardly as the output on the command prompt. I used a recursive returning-value (string) function to perform the whole process of getting the given string in backward and returning it to the main function to be displayed on screen, as you can see below:
#include <iostream>
#include <string>
using namespace std;
string rev(string, int);
int main() {
string let;
cout << "Enter your string: ";
cin >> let;
cout << "The string in reverse is: " << rev(let, let.length());
cout << endl;
return 0;
}
string rev(string x, int y) {
if (y != 0 )
return x[y - 1] + rev(x, y - 1);
else
return "\0";
}
What I don't get about the process, is that while the concatenation performed on the rev function, recursively, and with the char variables works correctly and returns the string in backward to the main function, trying to concatenate the char variables normally like this gives rubbish as the output:
#include <iostream>
#include <string>
using namespace std;
int main() {
string hd;
string ah = "foo";
hd = ah[2] + ah[1] + ah[0];
cout << hd << endl;
return 0;
}
And even if I add to the "hd" chain "\0", it still gives rubbish.
Upvotes: 0
Views: 117
Reputation: 11317
How about making use of everything that's already available?
string rev(const string &x) { return string{x.rbegin(), x.rend()}; }
Reverse iterators allow you to reverse the string, and the constructor of string with 2 iterators, constructs an element by iterati from begin to end.
Upvotes: 0
Reputation: 234635
Writing instead
hd = ""s + ah[2] + ah[1] + ah[0];
will, informally speaking, put +
into a "concatenation mode", achieving what you want. ""s
is a C++14 user-defined literal of type std::string
, and that tells the compiler to use the overloaded +
operator on the std::string
class on subsequent terms in the expression. (An overloaded +
operator is also called in the first example you present.)
Otherwise, ah[2] + ah[1] + ah[0]
is an arithmetic sum over char
values (each one converted to an int
due to implicit conversion rules), with the potential hazard of signed
overflow on assignment to hd
.
Upvotes: 1
Reputation: 687
Your first example implicitly converts characters to strings and uses appropriate operator +
While your second example is adding up characters
https://en.cppreference.com/w/cpp/string/basic_string/operator_at
returns reference to character at position
Upvotes: 1