you can easily use class string:
#include <iostream>
#include <string>
int main()
{
std::string s1 = "Hello", s2;
for(int i(s1.length() - 1 ); i >= 0; i--)
s2+= s1[i];
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
return 0;
}
- to solve it in your way using character array the consider:
1- you input the sizeOfString one question:
what about the input with cin overflows or underflows the input size (smaller or bigger)???
eg:
sizeOfString = 5;
cin >> charray3; // "ab" now the size is only 3 (+ null terminator)
so writing:
charray3[sizeOfString - 1] = 'c'; // charray3[5 - 1] // charray[4]
while charray4 is not inputted because you inputted only charray3[0] and charray3[1] so as a result a segfault.
to correct it you have to do some extra work:
#include <iostream>
using namespace std;
int main()
{
// Reversing A String
cout << "welcome to string reverser" << endl;
int sizeOfString;
cout << "please input size of string" << endl;
cin >> sizeOfString; // you specified size
cin.ignore(1, '\n'); // clean the input buffer
char* charray3 = new char[sizeOfString + 1];
//cin>>charray3; use getline instead to get whitespaces
cout << "enter text: " << endl;
cin.getline(charray3, sizeOfString); // what if the user enter a text smaller or bigger than sizeOfString???
charray3[sizeOfString] = '\0';
//to correct it:
// take effects of input on sizeOfString
sizeOfString = strlen(charray3);
cout << "before reversing: " << endl;
cout << charray3 << endl;
// to reverse it create a temporary array:
char* pTmp = new char[sizeOfString + 1];
for(int i(sizeOfString-1), j = 0; i >= 0; i--, j++)
pTmp[j] = charray3[i];
pTmp[sizeOfString] = '\0';
cout << "after reversing: " << endl;
cout << pTmp << endl;
// don't forget to clean:
delete[] charray3;
delete[] pTmp;
return 0;
}
sizeOfStringsupposed to be the number of bytes the string occupies in memory or the number of characters in it? You say you setsizeOfStringto 3 for "abc", implying it's the number of valid characters in it, but then you use it as the size of the array to allocate implying it's the memory size. (If you don't understand why it can't be both, you don't understand C-style strings.)char charray3[sizeOfString];is not standard C++ whensizeOfStringis not a constant expression.std::string, not char array.