mur7ay
mur7ay

Reputation: 833

Reversing a String With Pointers

I'm attempting to write a simple program that will reverse a users input utilizing pointers. This is my first time working with pointers and in theory my program seems like it would work: have an array, write the users input to the array, point one pointer to the head and the other to the end and have the while loop do the rest. However, my program isn't working properly. My question is, what exactly am I doing wrong?

Heres my code:

#include <iostream>
#include <string>
using namespace std;

int main() {

    char user_input[1000] = " ";

    cout << "Enter a word to be reversed: " << endl;
    cin >> user_input;

    int myChar = sizeof(user_input) - 1;

    char *start = user_input;
    char *end = user_input + myChar - 1;

    while (start < end) {
        char save = *start;
        *start = *end;
        *end = save;

        start++;
        end--;
    }

    cout << user_input;

} 

And my output: 

Enter a word to be reversed: 
hello <--- my input
      <--- no output

Upvotes: 0

Views: 91

Answers (4)

KJP
KJP

Reputation: 1

You can also write a strlen function by yourself.
The end of the user's input would be the index of the first 0 as an int or '\0' AS a char.

Upvotes: 0

Rishabh Mamgain
Rishabh Mamgain

Reputation: 23

declare user_input as char *user_input=new char[1000]


so what is the problem ??


well the problem is when you take input from user in user_input it take it as user_input[0] so either run a for loop from 0 to n-1 or use my way given above moreover output is still errorneous that i will leave for u .....

Upvotes: 2

owacoder
owacoder

Reputation: 4873

The line

int myChar = sizeof(user_input) - 1;

should be

#include <string.h>

int myChar = strlen(user_input);

Currently, you are reversing all 1000 characters in your array. The characters beyond the end of your inputted string are not initialized, so you should only reverse the number of characters the user input. strlen() finds the length for you.

Another alternative: use the standard library.

Upvotes: 5

Emil Laine
Emil Laine

Reputation: 42828

sizeof(user_input) is always 1000 since user_input is an array of 1000 1-byte elements.

You need to use strlen instead. It returns the index of the terminating null character.

Upvotes: 3

Related Questions