2

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.

Miller
  • 21
  • 3
  • Hello, you want to change your statement newString[(end-1)-x] = string[x]; to newString[x] = string[end-1-x] . Secondly, as I see there should be no length limit except 50, are you sure its not because you are using a string with spaces? – MrSykkox Oct 23 '18 at 01:45
  • tried it, this doesn't do anything different, my code still doesn't work for words bigger than 7 letters. yea my input word is "abigword", no spaces. – Miller Oct 23 '18 at 01:48
  • have you tried initializing `newString` to all NULLs or otherwise appending a NULL to the end of `newString`? – bruceg Oct 23 '18 at 01:50
  • is there a reason that this would work? I'll try it but if the code works for a 4 letter word such as "test", why would this change be necessary for a word bigger than 7 letters. Edit: ok just tested this, it works now though still unclear as to why, but thanks regardless. – Miller Oct 23 '18 at 01:53
  • See my answer below for the explanation – bruceg Oct 23 '18 at 01:55
  • 1
    `scanf("%50s", string);` writes one beyond the end of your string array for strings with greater-than or equal to `50` chars. `scanf` requires `'n-1'` as the *field-width* modifier to the `"%s"` conversion specifier. (which stops reading on encountering the 1st whitespace). Use `fgets()` instead of `scanf`... (and at minimum **check the return** for whatever function you use) – David C. Rankin Oct 23 '18 at 02:13

3 Answers3

0

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.

bruceg
  • 2,433
  • 1
  • 22
  • 29
  • This will fail miserably with a string such as "this isn't going to work at all.". – l'L'l Oct 23 '18 at 02:07
  • Yes. The OP's scanf will only work with a single string. So, he will need a more sophisticated mechanism to read in a string if the specified input allows spaces or other special characters in the input. – bruceg Oct 23 '18 at 02:12
0

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.

Bwebb
  • 675
  • 4
  • 14
0

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.

  • ok I copied your code exactly into my C workspace and got "error: implicit declaration of function 'strrev'; did you mean 'strlen'?" – Miller Oct 23 '18 at 07:44
  • https://stackoverflow.com/questions/8534274/is-the-strrev-function-not-available-in-linux –  Oct 23 '18 at 08:49
  • Or did you use #include (if you are on windows)? It is helpful to say, in general, how your workspace is configured. –  Oct 23 '18 at 08:54
  • I did use #include and on a mac. It's not really a big deal anyway since I know how to do it myself but thanks for the help anyway – Miller Oct 23 '18 at 12:00