Revert a standard input line in C

Asked

Viewed 30 times

0

I am trying to get the following output if the imput be: hi mom the output sera: eam io

the code I made, trying to train recursion was:

#include <stdio.h>

void reverse(char *arr)
{
    if (*arr != EOF)
        reverse((arr + 1));
    printf("%c", *arr);
}

int main()
{
    char input;

    scanf("%s[^\n]", &input);
    reverse(&input);
    return (0);
}

works for the first word, but returns a strange result after giving a space;

Can anyone explain to me why?

1 answer

0

What prevents you from reading the two words that are written is the scanf that’s done as:

%s[^\n]

When it should be:

%[^\n]s

But there are several other details that are not right:

  • You have to read a string (%s) to an array of char and not a char simple (a letter).
  • The string end test has to be done with \0 or 0 and not EOF.
  • You are showing the character on the console, even if it is already the last (the '\0').

Fixing all this your code gets like this:

#include <stdio.h>

void reverse(char *arr)
{
    if (*arr != '\0'){ //testa o fim com '\0'
        reverse(arr + 1); 
        printf("%c", *arr); //só mostra se não for \0
    }
}

int main()
{
    char input[30]; //agora string em vez de char

    scanf("%29[^\n]s", input); //formato correto
    reverse(input); //sem o &
    return 0;
}

Check it out at Ideone

  • Perfect! Thank you very much, if I may, I’d like to ask you a few questions. Because the Voce input does not need to pass the symbol &? which represents %29 before [ n]s ?

  • @Piero You don’t need to pass the & because the array of char works as if it were already a pointer. It has the %29 to ensure that only le 29 characters of the entry for the array as you have to reserve one for the terminator. If I read more than 29, I’d be overwriting the memory that it wasn’t yours.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.