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
@selbie is right ,
*strPtr++;
==>
++strPtr;
also add this before call convertToPigLatin
if(str[0] == '\0')
break;
And it works,the pigLatinOut.txt show work in Latin,but all in one line!
like this : (I know nothing about Latin,is that waht you want?):
pigLatinIn.txt
hello world!
I am line one!
I am line two!
I am line three!
pigLatinOut.txt
𬌿\q·ð¬Œ¿\q·ð¬Œ¿\q·ð¬Œ¿\q·
There are a variety of oddities in this code, but the problem you're asking about is created by your while loop in convertToPigLatin
. You loop while *strPtr != '\0'
, and \n
is certainly not \0
, so you are adding that to pStr
.
Now for the rest of the code, just a few comments:
strncat
to copy one character is odd usage. Typically, one would use simple character assignment instead (as in str1[i] = str2[j]
)*strPtr++
is incrementing the pointer and dereferencing it, but then doing nothing with the dereferenced value. You just want strPtr++
there.char str[] = "some string"
. You don't need to use array initialization syntax.Those are the ones that jumped out at me without a detailed reading. Good luck on your future assignments.
Edit to add that stepping through your code with a debugger is very valuable in these cases. You would see exactly where the newline is being added.
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.