Reputation: 1
I am trying to code a C++ program that takes a 5 character long string and then prints out the string with a new permutation with this order: 1st character, 3rd character, 5th character, 2nd character, 4th character. My code is as follows:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string key;
string p10;
cout << "Enter the five characters long string: ";
cin >> key;
p10 = key[0] + key[2] + key[4] + key[1] + key[3];
cout << p10 << endl;’
system(“pause”);
return 0;
}
The output (p10) is a random Greek letter every time I run it.
Please help!
Upvotes: 0
Views: 65
Reputation: 65166
The problem here is that when you use []
on a string, you're not getting back another string, but a single char
. A char
is actually just a small integer number (think character code), and if you use the +
operator with them, it'll add the numbers together. You'll end up with a more or less random character code, which is why you get greek letters.
If you want to keep the structure of the code as close to the original as possible, you can use substr
to get "one character strings" instead of plain char
s:
key.substr(0, 1) + key.substr(2, 1) + ...
The 1
signifies that you want one character from the specified offset.
Another way is to first construct a char array out of the characters and then turn it into a string:
char p10_arr[] = { key[0], key[2], ... };
string p10(arr, sizeof(arr));
And perhaps the nicest and most concise way is to use the initializer list syntax:
string p10 { key[0], key[2], ... };
Upvotes: 2