0

Why does the second strncpy give incorrect weird symbols when printing? Do I need something like fflush(stdin) ?

Note that I used scanf("%s",aString); to read an entire string, the input that is entered starts first off with a space so that it works correctly.

void stringMagic(char str[], int index1, int index2)
{
    char part1[40],part2[40];

    strncpy(part1,&str[0],index1);
    part1[sizeof(part1)-1] = '\0';//strncpy doesn't always put '\0' where it should
    printf("\n%s\n",part1);

    strncpy(part2,&str[index1+1],(index2-index1));
    part2[sizeof(part2)-1] = '\0';
    printf("\n%s\n",part2);
}

EDIT The problem seems to lie in

scanf("%s",aString);

because when I use printf("\n%s",aString); and I have entered something like "Enough with the hello world" I only get as output "Enough" because of the '\0'.

How can I correctly input the entire sentence with whitespace stored? Reading characters?

Now I use: fgets (aString, 100, stdin); (Reading string from input with space character?)

Community
  • 1
  • 1
Ho Pam
  • 435
  • 1
  • 4
  • 6
  • Check if the limits (index1 + 1) and (index2 - index1) actually are within the size of the char array part2. That might be causing it. Then, check if str is actually well formed. – SenselessCoder Oct 25 '16 at 11:19
  • fflush(stdin) is undefined behavior so you should never do that in any program. – Lundin Oct 25 '16 at 11:43
  • But up until now that works fine in my program. If you know an alternative I be more than happy to hear it (since sometimes after the first scanf the other scanf will fail) – Ho Pam Oct 25 '16 at 11:46

1 Answers1

1

In order to print a char sequence correctly using %s it needs to be null-terminated. In addition the terminating symbol should be immediately after the last symbol to be printed. However this section in your code: part2[sizeof(part2)-1] = '\0'; always sets the 39th cell of part2 to be the 0 character. Note that sizeof(part2) will always return the memory size allocated for part2 which in this case is 40. The value of this function does not depend on the contents of part2.

What you should do instead is to set the (index2-index1) character in part2 to 0. You know you've copied that many characters to part2, so you know what is the expected length of the resulting string.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • But then why is part1 working perfectly fine? I also use there the same line of code. But I understand your point there.. – Ho Pam Oct 25 '16 at 11:23
  • @HoPam my guess is - pure luck. If you don't set the null terminating character correctly some random data will be printed. However it may happen that the first symbol after the meaningful content is `\0`. This data is not initialized so it can be anything. – Ivaylo Strandjev Oct 25 '16 at 11:41
  • Will try your method and will let you know ! Thanks ! – Ho Pam Oct 25 '16 at 11:47