I am new to C++ and I recently learned pointers and references through u-demy lectures. After lectures, I am solving a problem to reverse a string using a separate function. I came up with a code but for some reason, I can access an individual char using [] notation (like reverse[0]
is equal to !) but when I print the whole string I get an empty string? What is causing this issue?
Thank you for your time in advance!
Here I have pasted my code:
#include <iostream>
// using namespace std;
std::string reverse_string(const std::string &str) {
std::string reversed;
size_t size {str.length()};
for(int i{}; i < size/2; i++) {
reversed[i] = str[(size-1)-i];
reversed[(size-1)-i] = str[i];
}
return reversed;
}
int main() {
// Write C++ code here
std::string input = "Hello, World!";
std::string reversed = reverse_string(input);
std::cout << reversed << std::endl; //I get nothing, BUT
std::cout << reversed[0] << std::endl //here I do get a '!'
return 0;
}