Issues with string processing in C

后端 未结 3 1008
离开以前
离开以前 2021-01-25 14:02

I\'m stuck on a HW assignment where I\'m required to write a program that transforms a bunch of English words (in a list separated by new lines in a input .txt file) into a bunc

3条回答
  •  梦谈多话
    2021-01-25 14:33

    The problem lies not in strncat, but in your input:

    fgets(str, 29, fileInPtr);                //Assigns word to *char
    str[29] = '\0';                           //Optional: Whole line
    

    If you enter something other than 29 characters, the hard return is not overwritten. Use this instead:

    str[strlen(str)-1] = 0;
    

    .. actually, this will always overwrite the 29th character, even if it isn't a hard return (when you entered more than 29 characters). So a better solution would be

    char *ptr = strchr(str, '\n');
    if (ptr) *ptr = 0;
    

    You cannot use MAX_STR_SIZE for this either (which you defined-but didn't use in your code), since fgets

    [r]eads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. (http://www.cplusplus.com/reference/cstdio/fgets/)

    -- the last character could be the terminating zero, or a hard return.

提交回复
热议问题