First of all function main in C++ and in C shall have return type int
. So it shall be defined as
int main()
{
//...
Secondly the member function size()
has an unsigned integral return type. So it would be better to write
std::string::size_type n = str1.size();
Thirdly you should use C++ streams instead of C streams in a C++ program. C function printf is unable to output objects of type std::string. So you have to pass on a pointer to character array that is returned by member function c_str()
The loop could be written the following way
std::string::size_type n = str1.size();
for ( std::string::size_type i = 0; i < n; i++ )
{
rev[i] = str1[n - i - 1];
}
Take into account that you could get the reversed string simpler. For example
std::string rev( str1.rbegin(), str1.rend() );
without using any loop.
So the program could look as
#include <iostream>
#include <string>
int main ()
{
std::string str1 = "abcde";
std:: string rev( str1.rbegin(), str1.rend() );
std::cout << str1 << std::endl;
std::cout << rev << std::endl;
std::string::size_type n = rev.size();
for ( std::string::size_type i = 0; i < n / 2; i++ )
{
// std::swap( rev[i], rev[n - i - 1] );
char c = rev[i];
rev[i] = rev[n - i - 1];
rev[n - i - 1] = c;
}
std::cout << str1 << std::endl;
std::cout << rev << std::endl;
}