Problem constructing a string/char array

Hi, I am new to C++. I'm trying to reverse a word input, but I've done something wrong, and it is not couted correctly. It can, however, cout each character, so I am not sure where I have gone wrong. Also, whenever I use a string type pointer, the program crashes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstring>

using namespace std;
int main()
{
    string word;
    cout << "Enter a word.\n";
    cin >> word;
    //string* reverse = new string[word.size()+1];
    char* reverse = new char[word.size()+1];
    int i, j;
    for (i = 0, j = word.size(); i<=word.size(); i++,j--)
        {
            reverse[i] = word[j];
           //  cout << reverse[i] << endl;
        }
    reverse[word.size()+1]='\0';
    cout << reverse << endl;
    delete [] reverse;
    return 0;
}

Thanks for any help.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <algorithm>

using namespace std;
int main()
{
    string word;
    cout << "Enter a word.\n";
    cin >> word;
    reverse(word.begin(),word.end());
    cout << word;
    return 0;
}
Thanks for the reply, but it's more of a matter of understanding what I did wrong than actually getting the solution by another means.
Try this:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstring>

using namespace std;
int main()
{
    string word;
    cout << "Enter a word.\n";
    cin >> word;
    //string* reverse = new string[word.size()+1];
    char* reverse = new char[word.size()+1];
    int i, j;
    
    for (i = 0, j = word.size(); i<=word.size(); i++,j--)
        {
	  cout << (int)word[j] << endl;
            reverse[i] = word[j];
             cout << reverse[i] << endl;
        }
    reverse[word.size()+1]='\0';
    delete [] reverse;
    return 0;
}


and remember that in a char array, the end of the word is marked by the first zero value you come to.
Ah, you're right about the indexing. I should have caught that. It should be
1
2
string* reverse = new string[word.size()];
char* reverse = new char[word.size()];

and
 
for (i = 0, j = word.size()-1; i<=word.size()-1; i++,j--)

and
 
reverse[word.size()]='\0';


Though when I try it with type string, I am still getting a crash. (The debugger lists only the address for reverse when it is pointing to string memory.) EDIT: Now I see the error of my ways: my code preallocates an array of strings, and that string allocation is much different.
Last edited on
Topic archived. No new replies allowed.