how to assign uninitialized string value from another string in C++ -
i new programming. question may silly helpful if can guide me.
please see code below:
#include <iostream> #include <string> using namespace std; int main() { cout << "you have choose reverse text" << endl; string inputstring; string outputstring; cout << "enter string want reverse" << endl; getline(cin, inputstring); int n = inputstring.length(); (int = 0; < n; i++) { outputstring[i] = inputstring[n - 1 - i]; // problem in line } }
till here works fine inputstring[n - 1 - i]
when try assign value outputstring
. getting error.
outputstring
empty, you're accessing out of bounds here:
outputstring[i] = inputstring[n - 1 - i];
you have ensure outputstring
has length of @ least n
time enter loop. there different ways of achieving that.
one solution create size n
after reading in inputstring
. here, create filled *
:
std::string outputstring(n, '*');
you can resize string after creation:
outputstring.resize(n);
now can access outputstring[n]
n
in range [0, n)
. makes loop valid. see this working example.
alternatively, consider reversing inputstring
in-place. note in real code, can done std::reverse
:
std::reverse(inputstring.begin(), inputstring.end());
Comments
Post a Comment