I am trying to read in a text file char by char and append each char to a string.
This code here outputs what I expect, showing each individual char:
char currentStr[MAX_WORD_LEN] = "";
char cStrConvert[1] = "";
char c;
while((c = fgetc(filePtr)) != EOF)
{
cStrConvert[0] = c;
printf("\ncStrConvert:%s\n", cStrConvert);
//strcat(currentStr, cStrConvert);
printf("\ncurrentStr: %s\n", currentStr);
}
This is the output of the above:
cStrConvert:w
currentStr:
cStrConvert:o
currentStr:
cStrConvert:w //and so on for all the chars in the text file
However, when I make an attempt to append these chars to a string via strcat(); the code below,
char currentStr[MAX_WORD_LEN] = "";
char cStrConvert[1] = "";
char c;
while((c = fgetc(filePtr)) != EOF)
{
cStrConvert[0] = c;
printf("\ncStrConvert:%s\n", cStrConvert);
strcat(currentStr, cStrConvert);//try to append to the string
printf("\ncurrentStr: %s\n", currentStr);
}
cStrConvert:w
currentStr: w
cStrConvert:ow
currentStr: wow
cStrConvert:wwow
currentStr: wowwwoww
I have distilled this behavior to the one line that changes between the two code blocks, however I have no clue as to why it is not just appending each char to the currentStr. Additionally, strcat() seems to be changing cStrConvert as well.
Edit 2: Solution
I changed my definition of
char cStrConvert[1] = "";
to
char cStrConvert[2] = "";
to account for, and to be able to hold the null terminator character