我想,你会从文件中读取的不只是一个角色,所以看下面的例子:
#define STR_SIZE 10
// STR_SIZE defines the maximum number of characters to be read from file
int xp;
char str[STR_SIZE + 1] = { 0 }; // here all array of char is filled with 0
// +1 in array size ensure that at least one '\0' char
// will be in array to be the end of string
int strCnt = 0; // this is the conter of characters stored in the array
while (1) {
xp = fgetc(f);
char xpchar = xp;
//convert xpchar into a string
str[strCnt] = xpchar; // store character to next free position of array
strCnt++;
if (strCnt >= STR_SIZE) // if array if filled
break; // stop reading from file
}
而且你的文件指针变量的名字 - filename
看起来很奇怪(filename
好名字用于存储文件的名称,但fgetc
和getc
需要FILE *
),所以请在你的程序字符串变量您有类似:
FILE * f = fopen(filename, "r");
或考虑为filename
改变名称。
创建一个'char'数组并开始存储到它....实际上你的问题是什么? –
一个字符串只是一个字符数组,在最后有一个空字符。 – Barmar
我可以打印; printf(“%c”,xpchar);但是我想用%s。 –