in C, I'm looking for a simple solution for my code that works until a word with 8 or more letters is entered

I'm pretty very relatively new to C, I'm trying to reverse a string with this code and it works until a word with 8 or more letters is entered and I don't quite understand why.

int main()
{
  char string[50], newString[50];
  int end, x;

  printf("Enter a string: \n");
  scanf("%50s", string);

  end = strlen(string);

  printf("%d\n", end);

  for(x=0; x < end; x++){
      newString[(end - 1) - x] = string[x];
  }

printf("%s", newString);
}

little bit strange wording of the question but it wouldn't let me ask the question since 'my title was too similar to other questions asked' even I have looked and haven't found what I want to know.

3 answers

  • answered 2018-10-23 01:54 bruceg

    You have not added a NULL terminator to the end of your newString buffer. Try adding this line after the loop, and before you print out.

    newString[end] = '\0';
    

    You code as it is would produce random results depending on what the runtime has placed in the newString buffer. If you're lucky there will be a NULL terminator at the right spot, but it seems like you are unlucky with short strings.

  • answered 2018-10-23 02:05 Bwebb

    what bruceg said should work, but in general you should probably get in the habit of initializing the variables you use.

    char string[50] = {0};  //declare and initialize to zero all elements before it is used.
    char newString[50] = {0};
    int x = 0;
    int end = 0;
    

    This way when you copy into newString you know that newString[i] is 0 and %s will hit the null terminator after the copy is done.

  • answered 2018-10-23 06:21 Syed Irfan Ahmed

    in C, I'm looking for a simple solution for my code that works until a word with 8 or more letters is entered

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX 15
    void trim_newline(char str[]);
    
    int main()
    {
        char s[MAX + 1] = "";
    
        printf("Enter string: ");
        fgets(s, MAX, stdin);
        trim_newline(s);
        if (strlen(s) >=8)
        {
            printf("Len >= 8\n");
            printf("Quitting ...\n");
        }
        else
        {
            printf("s = %s\n", s);
            printf("Length of s = %d\n", (int)strlen(s));
            printf("Reversed s = %s\n", strrev(s));
        }
    
        return EXIT_SUCCESS;
    }
    // -----------------------
    void trim_newline(char str[])
    {
        if(str[strlen(str) -1] == '\n')
            str[strlen(str) - 1] = '\0';
    }
    

    strrev() reverses a string. No need to redo it, unless your teacher asked for it specifically. fgets() is a secure way to get strings. If a newline is found, it must be trimmed. You can add the condition about zero-length (user pressing Enter only) yourself.