Search code examples
c++algorithmreversec-stringsfunction-definition

Trying to reverse a C string


I cannot use any c functions except strlen(), and I also cannot use strings. I have been at this for an unfortunate amount of time. I keep getting weird characters as part of the output. i.e question marks and essentially weird alt codes is what it looks like.

#include <iostream>
#include <cstring>

using namespace std;

int lastIndexOf(const char*, char[]);
void reverse(char*);
int replace(char*, char, char);

int main() {
  int i = 0, count = 0, counter = 0, SIZE = 100;
  char charArray[SIZE];
  cout << "Enter a string of no more than 50 characters: ";
  cin.getline(charArray, SIZE);
  reverse(charArray);
}

void reverse(char s[])
{
  int n = 100;

  for (int i = 0; i < n / 2; i++) {
    swap(s[i], s[n - i - 1]);
    cout << (s[i]);
  }
}

I have tried several different things, swap function, using pointers to manually swap them with a temp variable. So I went to the internet to see what other people did, but to no avail. I am convinced there is a simple solution.


Solution

  • The function uses a magic number 100

    int n = 100;
    

    though in main there is a prompt to enter no more than 50 characters.

    cout << "Enter a string of no more than 50 characters: ";
    

    You need to calculate the length of the passed string by using the standard C function strlen.

    The function can look the following way

    char * reverse( char s[] )
    {
        for ( size_t i = 0, n = std::strlen( s ); i < n / 2; i++ )
        {
            std::swap( s[i], s[n-i-1] );
        }
    
        return s;
    }
    

    Pay attention to that variable length arrays is not a standard C++ feature.

    You should write

    const size_t SIZE = 100;
    char charArray[SIZE];