I am very new to programming. My question may be silly but it will be helpful if someone can guide me.
Please see my code below:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "you have choose to Reverse the text" << endl;
string inputstring;
string outputstring;
cout << "Enter the string you want to reverse" << endl;
getline(cin, inputstring);
int n = inputstring.length();
for (int i = 0; i < n; i++)
{
outputstring[i] = inputstring[n - 1 - i]; // problem in this line
}
}
Till here it works fine inputstring[n - 1 - i]
but when I try to assign its value to outputstring
. I am getting error.
outputstring
is empty, so you're accessing it out of bounds here:
outputstring[i] = inputstring[n - 1 - i];
You have to ensure outputstring
has length of at least n
by the time you enter the loop. There are different ways of achieving that.
One solution is to create it with size n
after reading in to inputstring
. Here, we create it filled with *
:
std::string outputstring(n, '*');
You can also resize the string after creation:
outputstring.resize(n);
Now you can access outputstring[N]
for N
in the range [0, n)
. This makes your loop valid. See this working example .
Alternatively, you could consider reversing inputstring
in-place. Note that in real code, this can be easily done with std::reverse
:
std::reverse(inputstring.begin(), inputstring.end());
You just use the assign
member function of std::string
outputstring.assign(inputstring);
or you could even simpler use its operator =
like
outputstring = inputstring;
Or, if you just want to assign parts of the string, you can insert , replace , append and use resize to resize the string
As a rule of thumb, always read the documentation related to any C++ feature you are using, so if you use std::string
you have to read its documentation before starting coding (to be able to choose the right functions for the job)
Reading the first few chapters of a good book on C++ programming before even typing any C++ code will be very helpful.
OF course learn C++11 or C++14, not some older version of the standard.
outputstring is empty. So during accessing to its i'th element you program causes undefined behavior ( link , Exception safety section) . Just change last lines
for (int i = 0; i < n; i++)
{
outputstring[i] = inputstring[n - 1 - i]; // problem in this line
}
with
outputstring.reserve(n); // reserve is optional. Use it just for memory allocating optimization..
for (int i = 0; i < n; i++)
{
outputstring += inputstring[n - 1 - i]; // problem in this line
}
Operator += appends char or string to initial string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.