C语言中使用strcat()逐字符追加文本内容到字符串异常问题
逐字符读取文本文件并追加字符串的C语言问题
我尝试在C语言中逐字符读取文本文件,并将每个字符追加到字符串中。
以下代码能正常输出每个单个字符:
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); }
对应的输出为:
cStrConvert:w currentStr: cStrConvert:o currentStr: cStrConvert:w //and so on for all the chars in the text file
但当我尝试通过strcat()将字符追加到字符串时,使用以下代码:
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
我定位到问题出在启用strcat()的那一行,但不清楚为何无法正常追加字符,且strcat()似乎还修改了cStrConvert的内容。
解决方案
将定义:
char cStrConvert[1] = "";
修改为:
char cStrConvert[2] = "";
以容纳空终止符字符。
内容的提问来源于stack exchange,提问作者tothemax
相关产品推荐
相关产品推荐

