0
votes

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?)

1
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
fflush(stdin) is undefined behavior so you should never do that in any program. - Lundin
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

1 Answers

1
votes

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.