在C中将ASCII代码转换为字符串

时间:2017-08-01 00:49:53

标签: c arrays string

我正在尝试基于单个ASCII代码创建一个char数组。即使将“num”强制转换为char:

,下面的代码也无法正确编译
//Returns the ASCII counterpart of a number, such as 41 = A, 42 = B, 43 = C, etc.
char numToASCII(int num) {
    char[] string = {(char)num, "\0"};
    return string;
}

对于我给出的任务,“string”是字符数组/字符串而不是单个字符非常重要。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

必须将数组初始化为常量表达式,如果要返回数组,函数应返回指针。 如果您只想返回一个字符,请改用以下代码:

char numToASCII(int num) {
    return (char)num;
}

如果要返回包含该字符的字符串,则应使用以下代码:

#include <stdlib.h>

char *numToASCII(int num) {
    /*
     * Use malloc to allocate an array in the heap, instead of using a
     * local array. The memory space of local array will be freed after
     * the invocation of numToASCII.
     */
    char *string = malloc(2);
    if (!string)
            return 0;
    string[0] = num;
    string[1] = 0;
    return string;
}

使用free()功能释放malloc()分配的空间。

答案 1 :(得分:0)

试试这个.. 您想要找到ASCII码的字符,然后尝试以下代码:

#include<stdio.h>
int main()
{
    int num;
    printf("\nEnter ASCII Code Number:\t");
    scanf("%d", &num);
    printf("\nASCII Value of %d: \t%c", num, num);
    printf("\n");
    return 0;
}

在此代码中,它将从用户处获取ASCII代码,并且它将默认打印ASCII代码的字符。

答案 2 :(得分:0)

不确定这是否有帮助,但从文件中提取文本会以 ascii 格式返回,我需要一个字符串并通过检查字符串长度来绕过它,抱歉额外的步骤,因为我也是新手。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    char firstbuff[yourchoice];
    char secondbuff[yourchoice];
    char sentence[yourchoice];
    int stringlenght;

    fp = fopen("test.txt", "r");

    //Here add a means of counting the lines in the file as linecount
    for(int j = 0; j < linecount; j++)
    {
        fgets(firstbuff; 1000; fp);
 //get string length and use for loop to individually ascii copy as characters into array
        stringlength = strlen(firstbuff);
        for(int i = 0; i < stringlength; i++)
        {
           secondbuff[i] = (char)firstbuff[i];
        }
        //string concat
        strcat(sentence, secondbuff);
    }
    printf("%s\n", sentence);
    fclose(fp);
        
}