2016-08-15 77 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改变名称。