2016-08-15 74 views
-4

我正在使用fgetc從文件中讀取,並且這樣做使得我有一個字符。但是,我想將此char轉換爲一個字符串,以便我可以在其上使用strtok函數。我會如何去做這件事?如果你願意在C中將char轉換爲字符串

char str[] = {ch, '\0'}; 

或者,使用複合字面常量做同樣的:

int xp; 
while(1) { 
    xp = fgetc(filename); 
    char xpchar = xp; 
    //convert xpchar into a string 
} 
+1

創建一個'char'數組並開始存儲到它....實際上你的問題是什麼? –

+0

一個字符串只是一個字符數組,在最後有一個空字符。 – Barmar

+0

我可以打印; printf(「%c」,xpchar);但是我想用%s。 –

回答

1

只需創建一個數組有兩個項目,你的性格和空終止

(char[]){ch, '\0'} 

在表達式中可以使用複合文字直接轉換您的字符:

printf("%s", (char[]){ch, '\0'}); 
0

我想,你會從文件中讀取的不只是一個角色,所以看下面的例子:

#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好名字用於存儲文件的名稱,但fgetcgetc需要FILE *),所以請在你的程序字符串變量您有類似:

FILE * f = fopen(filename, "r"); 

或考慮爲filename改變名稱。