我想,你會從文件中讀取的不只是一個角色,所以看下面的例子:
#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。 –