簡體   English   中英

將int轉換為char * C

[英]Convert int to char* C

所以我試圖從文件中讀取單詞。 但是,我必須使用putchar(ch) ,其中ch是一個int 如何將ch轉換為字符串(char *),以便將其存儲在char *變量中,並將其傳遞給另一個以char *為參數的函數。 我實際上只是想存儲它而不打印它。

這就是我所擁有的:

int main (void)
{
   static const char filename[] = "file.txt";
   FILE *file = fopen(filename, "r");
   if ( file != NULL )
   {
      int ch, word = 0;
      while ( (ch = fgetc(file)) != EOF )
      {
         if ( isspace(ch) || ispunct(ch) )
         {
            if ( word )
            {
               word = 0;
               putchar('\n');
            }
         }
         else
         {
            word = 1;
            putchar(ch);
         }
      }
      fclose(file);
   }
   return 0;
}

sprintf(char_arr, "%d", an_integer);

這使得char_arr等於char_arr字符串表示an_integer (如果您想知道,這不會打印任何內容到控制台輸出,只是“存儲”它)一個示例:

char char_arr [100];
int num = 42;
sprintf(char_arr, "%d", num);

char_arr現在是字符串"42" sprintf自動將空字符\\0char_arr

如果要在char_arr的末尾附加更多內容,可以執行以下操作:

sprintf(char_arr+strlen(char_arr), "%d", another_num);

“ + strlen”部分是這樣,因此它開始在末尾追加。

此處提供更多信息: http : //www.cplusplus.com/reference/cstdio/sprintf/

因此,您只有一個char類型的值,即int8_t (在某些系統上為uint8_t )。 您已將它存儲在int ,因此fgetc可以返回-1來返回錯誤,但仍然可以返回任何8位字符。

單個字符只是8位整數,您可以將其存儲為任何大小的整數變量而不會出現問題。 將它們放在結尾為零字節的數組中,您將得到一個字符串。

char buffer[10] = {0};
int c = 'H';
buffer[0] = c;
// now buffer holds the null-terminated string "H"
buffer[1] = 'e';
buffer[2] = 'l';  // you can see where this is going.
c = buffer[1];  // c = 'e' = 101
  // (assuming you compile this on a system that uses ASCII / unicode, not EBCDIC or some other dead character mapping).

注意,以字符串結尾的零字節進入緩沖區是因為我對其進行了初始化。 使用數組初始值設定項會將初始設定項列表中未提及的所有元素清零。

為了將單個字符表示為字符串,我發現使用一個簡單的2字符緩沖區與其他方法一樣容易。 您可以利用以下事實:將字符串解引用指向第一個字符,然后簡單地將希望表示的字符分配為字符串。 如果聲明時已將2字符緩沖區初始化為0 (或'\\0' ),則確保字符串始終以null-terminated

簡短的例子

#include <stdio.h>

int main (void) {

    int ch;
    char s[2] = {0};
    FILE *file = stdin;

    while ( (ch = fgetc(file)) != EOF ) {
        *s = ch;
        printf ("ch as char*: %s\n", s);
    }

    return 0;
}

使用/輸出

$ printf "hello\n" | ./bin/i2s2
ch as char*: h
ch as char*: e
ch as char*: l
ch as char*: l
ch as char*: o
ch as char*:

注意:您可以在while條件中添加&& ch != '\\n'以防止打印換行符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM