Hi there,
New to C++ and trying to write a short program to reverse the characters in a word. Im having trouble converting the string to a char array. Here is the code:
[code]
#include "stdafx.h"
#include #include #include using namespace std;
int main()
{
string org;
string end;
cin >> org;
int num = org.size();
char reversal[num];
strcpy(reversal, org.c_str());
for (int a = num; a >= 0; a--)
{
cout << reversal[a];
}
cout << endl;
return 0;
}
[/code]
Im getting three errors. All are on the strcopy() line:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'reversal' : unknown size
Im using Visual C++ to compile.
Any advice you can give is much appreciated and if there is a more efficient way of doing this please let me know. Thanks again!
Pete.
Comments
end += *rit;
}
[/code]
This uses the reverse iterator of the string class to iterate backwards through the collection and appends each character to the new string.
[code]
char* reversal = new char [num];
[/code]
Pete.
{
std::string t;
std::copy(s.rbegin(),s.rend(),std::back_inserter(t));
return t;
}[/code]
Can be rewritten simply as:
[code]std::string ReverseString(const std::string& s)
{
return std::string(s.rbegin(),s.rend());
}[/code]
...and, put that way, it almost doesn't even seem to deserve its own function.
Don't forget a C-style string (null terminated char array) needs that extra bit of space for the null terminating character. If it doesn't have a null it really isn't a "string" but rather simply a char array.
...and remember to always [italic]delete[/italic] what you [italic]new[/italic].
: function.
I purposefully post 'trivial' code on my website (http://richelbilderbeek.nl/CppWhyTrivialCode.htm): the beginner finds what he/she is looking for. The more advanced programmers use the one-line equivalent in his/her code directly.
If you would not mind...
Thanks, Bilderbikkel
if we dom't use it, how do this code do?
[url=http://www.halongluxuryjunk.com]Halong bay cruises[/url]- [url=http://www.waytosapa.com]Sapa tours[/url]- [url=http://www.songxanhcruisemekong.com]Song Xanh Sampan Cruise Mekong[/url]
if we dom't use it, how do this code do?
[url=http://www.halongluxuryjunk.com]Halong bay cruises[/url]- [url=http://www.waytosapa.com]Sapa tours[/url]- [url=http://www.songxanhcruisemekong.com]Song Xanh Sampan Cruise Mekong[/url]