Search code examples
c++stdstring

Unable to run reverse string program


I have recently started learning C++ and have written a few lines which accepts a string, displays the number of characters in it and also displays the reverse of the input string. This is what I have written.

#include <iostream>

int main()

{
  char string[25],rev_string[25];
  int counter=0,length=0;

  std::cout << "\n Enter the string : ";
  std::cin >> string;

  while(counter==!'\0')
  {
    counter=counter+1;
    length=length+1;
  }
  counter=0;

  std::cout << "The string has "<<length<<" characters in it.";
  while(length>=0)
  {
    rev_string[counter]=string[length];
    counter=counter+1;
    length=length-1;
  }

  std::cout << "\n The reverse of the given string is : "<<rev_string;

  return(0);
}

There is no error when I debug, however when I run the program, I get some unexpected value and the string length shows zero. Can you please point out where have I made mistakes.

This is what I get when I run the program.


Solution

  • while ( counter == !'\0' ) { … }
    

    Well, !'\0' is true, which as an integer is 1. So you have while (counter == 1), and counter is initialized to 0, making the expression immediately false, so the loop never executes.

    You probably meant to write != '\0'. But this is still a problem, since counter starts off with the value 0, and 0 != 0 is still false and the loop doesn’t loop.

    When you input Hey as your string, the characters H, e, y, and \0 are placed in the string variable. You want to find where that \0 character is, which we see is at string[3]. So why are you comparing counter with '\0'? Maybe you want string[counter]?


    When you get the number of characters in Hey, which is 3, you begin your reverse loop copying the \0 at index 3 to index 0 ... all 4 characters in the reverse order: \0, y, e, H. Unfortunately, the \0 at the start will mark the end of the string, so the string will appear empty..