2016-08-15 15 views
-4

私はfgetcを使ってファイルから読み込んでいますので、charを持つようになります。しかし、私はこの文字を文字列に変換して、strtok関数を使用できるようにしたいと思います。これをどうやってやりますか?あなたがする場合は、同じ操作を行うためにリテラル化合物を使用し、Cを文字列に変換する

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

単純に二つのアイテム、あなたのキャラクターとnull終端で配列を作成

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

複合リテラルを使用すると、式の中で直接文字を変換することができます。

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

は、私は、あなたがファイルからだけではなく、1文字を読んで、その次の例を見てしようとしているとします

#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の名前を変更する上だと思うが。

関連する問題