-2

I have just started coding in c++.

I wrote a code for reverse a string . I get null results.

void main ()
{
    string str1="abcde";string rev="";
    int n=str1.size();
    for(int i=n-1;i>=0;i--)
    {
        rev += str1[i];
    }
printf("%s \n", rev);
}

Could anyone please tell me.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
yesmina waah
  • 31
  • 1
  • 2
  • 2
    `%s` means "c-style null-terminated string", which `std::string` is not. If you are starting in C++ you might want to forget about the C functions such as `printf` completely. – Jon Aug 20 '14 at 22:06
  • 3
    Use `cout<<` to print a `std::string`. Or `printf` the _contents_ of the string instead of the string itself. The contents can be retrieved by calling `c_str()` on the string object. – Paweł Stawarz Aug 20 '14 at 22:06
  • 2
    `main` must return an `int` – quantdev Aug 20 '14 at 22:11
  • 2
    `std::reverse(str1.begin(), str1.end());` – Neil Kirk Aug 20 '14 at 22:17
  • @NeilKirk indeed, but the only difference is that the OP doesn't modify the original string in place, so strictly speaking it's not equivalent – quantdev Aug 20 '14 at 22:20

2 Answers2

5

std::string is being printed with %s format specifier. Try to change

printf("%s \n", rev);

with

printf("%s \n", rev.c_str());

Or as @Appleshell suggested, make it in C++ style:

std::cout << rev << "\n";

PS

Clearly, there are out-of-the-box ways to reverse strings, but I assume the idea was to have complete implementation.

AlexD
  • 32,156
  • 3
  • 71
  • 65
4

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335