0

I'm programming to reverse the word order, it's okay, but why does the first character of my string have an enter? And how do I avoid thist

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define TAM 50
    int main(){
        int i,j,t;
        char str[TAM],str2[TAM];
        printf("Digite a string:");
        fgets(str,TAM,stdin);
        setbuf(stdin,NULL);
        t = strlen(str);
        for(i=0,j=(t-1);i<t;i++,j--){
            str2[i] = str[j];
        }
        printf("str1:%s\nstr2:%s\n\n",str,str2);
    }

input:"oi"
output:" io"

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • 3
    The output is "\nio" because the input was "oi\n". – William Pursell Feb 20 '23 at 13:14
  • If you want to use the input without the `\n` (newline) character, then you must remove it after calling `fgets`. See the duplicate question for further information. – Andreas Wenzel Feb 20 '23 at 13:17
  • 1
    In my opinion, the best way for you to remove the newline character to add the line `str[strcspn(str,"\n")] = '\0';` immediately after the line in which you call `fgets`. That way, the newline character will be overwritten with a null terminating character, effectively removing it. If the string for some reason does not have a newline character, the terminating null character will be overwritten with the same value, which is harmless. – Andreas Wenzel Feb 20 '23 at 13:29

1 Answers1

0

It does not reverse the word order only reverses the string

char *reverse(char *str)
{
    char *end = str, *head = str;
    if(str)
    while(*end)
    {
        if(*end == '\n') *end = 0;
        else end++;
    }
    while(end < head)
    {
        char temp = *end;
        *end-- = *head;
        *head++ = temp;
    }
    return str;
}
0___________
  • 60,014
  • 4
  • 34
  • 74