简体   繁体   English

你可以在c中将int变量放入字符串吗?

[英]Can you put int variable into string in c?

Can you put an integer from a variable, for example:你能从一个变量中输入一个整数吗,例如:

int i=17;
char array[]= i;

and now i want to have现在我想要

array[3]= {1,7,\0}

I know it doesn't work this way but i dont know how to do it without some special functions, which i dont want to use.我知道它不能这样工作,但我不知道如何在没有一些我不想使用的特殊功能的情况下做到这一点。 Thank you for your help.感谢您的帮助。

this is what i came up with:这就是我想出的:

char array[];
    int counter = 172; //the number i want to put into string
    int i= 0;
    int p=0;
    float c = counter;
    int k=0, g=0, h=0;

    while(counter !=0){
        counter = counter /10;
        c= c/10;    
        p++;
    }
    while(p !=0){
        c=c*10;
        k=c;
        h= k-g;
        g=k*10;
        array[i] = h;
        i++;
        p--;
    }
    array[i]= '\0';

Use sprintf(buffer, "%d", i);使用sprintf(buffer, "%d", i);

Make sure that buffer is long enough to contain any possible number-string and the terminating \\0 byte.确保buffer足够长以包含任何可能的数字字符串和终止的\\0字节。

sprintf accepts everything that printf does, but sends its output to a string buffer instead of STDOUT. sprintf接受printf所做的一切,但将其输出发送到字符串缓冲区而不是 STDOUT。

If you really don't want to use sprintf, then here is a sample code snippet for you.如果您真的不想使用 sprintf,那么这里有一个示例代码片段供您使用。

    #define BASE 10
    #define MAXLEN 10
    int val = 153;
    char valstr[MAXLEN];

    //Reverse the int
    int valcpy = val;
    int valrev = 0;
    while(valcpy) {
        valrev *= BASE;
        valrev += valcpy % BASE;
        valcpy /= BASE;
    }

    //Convert to string
    int i = 0;
    while(valrev) {
        valstr[i] = valrev % BASE + '0';
        valrev /= BASE;
        i++;
    }
    valstr[i] = '\0';

    printf("%d = %s", val, valstr); //prints 153 = 153

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

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