I'm writing a program that reads user input and stores the value in a string. The value is supposed to be assigned to two char arrays, one of which is supposed to hold the characters in reversed order. However, the values in the reversed array don't show up in the terminal when I run the program. I also want to note that I am trying to achieve this without using pointers.
I've tried using a separate for loop together with a static int that gets incremented by 1 every iteration for reversed[str.length()] but the result stays the same. I've tested to output the values one by one, and somehow the characters show up in the terminal that way. I reckon that the values are assigned to the array after all, but aren't displayed when trying to output the whole text string at once. An explanation for why that is would be greatly appreciated!
Inside main():
string str;
cout << "Enter a word: ";
cin >> str;
cout << flush;
char input[str.length()];
char reversed[str.length()];
for(int i = 0; i <= str.length(); i++) {
input[i] = str[i];
reversed[i] = str[str.length() - i];
}
cout << "Your word: " << input << endl;
cout << "Reversed: " << reversed << endl;
Output:
Enter a word: hello
Your word: hello
Reversed:
std::reverse(begin(str), end(str));, done.str[str.length()]is undefined behavior, due to indexingstrout of bounds.