简体   繁体   English

将int转换为char * C

[英]Convert int to char* C

So I am trying to read the words from a file. 所以我试图从文件中读取单词。 However, I have to use putchar(ch) where ch is an int . 但是,我必须使用putchar(ch) ,其中ch是一个int How do I convert ch to a string (char *) so I can store it in a char * variable and pass it to another function that takes char * as a parameter. 如何将ch转换为字符串(char *),以便将其存储在char *变量中,并将其传递给另一个以char *为参数的函数。 And I actually just want to store it but not print it. 我实际上只是想存储它而不打印它。

This is what I have: 这就是我所拥有的:

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);

This makes char_arr equal to string representation of an_integer (This doesn't print anything to console output in case you're wondering, this just 'stores' it) An example: 这使得char_arr等于char_arr字符串表示an_integer (如果您想知道,这不会打印任何内容到控制台输出,只是“存储”它)一个示例:

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

char_arr now is the string "42" . char_arr现在是字符串"42" sprintf automatically adds the null character \\0 to char_arr . sprintf自动将空字符\\0char_arr

If you want to append more on to the end of char_arr, you can do this: 如果要在char_arr的末尾附加更多内容,可以执行以下操作:

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

the '+ strlen' part is so it starts appending at the end. “ + strlen”部分是这样,因此它开始在末尾追加。

more info here: http://www.cplusplus.com/reference/cstdio/sprintf/ 此处提供更多信息: http : //www.cplusplus.com/reference/cstdio/sprintf/

So you have a single value of char type, aka int8_t (or uint8_t on some systems). 因此,您只有一个char类型的值,即int8_t (在某些系统上为uint8_t )。 You have it stored in an int , so fgetc can return -1 for error, but still be able to return any 8bit character. 您已将它存储在int ,因此fgetc可以返回-1来返回错误,但仍然可以返回任何8位字符。

Single characters are just 8-bit integers, which you can store in any size of integer variable without problems. 单个字符只是8位整数,您可以将其存储为任何大小的整数变量而不会出现问题。 Put them in an array with a zero-byte at the end, and you have a string. 将它们放在结尾为零字节的数组中,您将得到一个字符串。

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).

Note that the string-terminating zero-bytes got into buffer because I initialized it. 注意,以字符串结尾的零字节进入缓冲区是因为我对其进行了初始化。 Using an array initializer zeroes any elements you don't mention in your initializer list. 使用数组初始值设定项会将初始设定项列表中未提及的所有元素清零。

To represent a single character as a character string, I find using a simple 2-character buffer to be as easy as anything else. 为了将单个字符表示为字符串,我发现使用一个简单的2字符缓冲区与其他方法一样容易。 You can take advantage of the fact that dereferencing the string points to the first character and simply assign the character you wish to represent as a string. 您可以利用以下事实:将字符串解引用指向第一个字符,然后简单地将希望表示的字符分配为字符串。 If you have initialized your 2-char buffer to 0 (or '\\0' ) when declared, you have insured your string is always null-terminated : 如果声明时已将2字符缓冲区初始化为0 (或'\\0' ),则确保字符串始终以null-terminated

Short Example 简短的例子

#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;
}

Use/Output 使用/输出

$ 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*:

Note: you can add && ch != '\\n' to the while condition to prevent printing the newline. 注意:您可以在while条件中添加&& ch != '\\n'以防止打印换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM