2016-02-26 102 views
1

我对C非常陌生。我想用3个整数和“/”构造一个字符串。如何在c中使用int变量创建字符串变量

例如,

int a=01; 
int b=10; 
int c=2012; 

char date = "a/b/c"; 

您可以请帮助,让我知道什么是正确的方法来做到这一点。

在此先感谢

+1

您不能在'char'中存储字符串,该字符只能包含一个字符(通常为一个字节)。 – MikeCAT

+1

简单地说:字符串是由'字符'的'数组'。 – nullpointer

回答

0

试试这个:

#include <stdio.h> 

int main() 
{ 
    int a=1; 
    int b=10; 
    int c=2012; 
    char date[11]; 

    sprintf(date, "%d/%d/%d", a, b, c); 
    printf("%s\n", date); 

    sprintf(date, "%02d/%02d/%04d", a, b, c); 
    printf("%s\n", date); 

    return 0; 
} 

这将打印日期两种格式。第二个零垫,而第一个没有。下面是输出:

1/10/2012 
01/10/2012 
+1

您应该在代码的顶部添加'#include '以使用'printf()'和'sprintf()'。 – MikeCAT

+0

@MikeCAT谢谢,我在我的代码中有这个,但是当我复制/粘贴时错过了它。我添加了它。 –

+0

非常感谢。有效 ! – Pri

1

您应该分配足够的缓冲区,并使用sprintf()

int a=01; /* this is octal value */ 
int b=10; 
int c=2012; 

char date[40]; /* 32-bit long integer will be at most 11 digits including sign in decimal */ 
sprintf(date, "%d/%d/%d", a, b, c); 
+0

非常感谢。有效 ! – Pri

0

使用sprintf,这将写入字符串,顾名思义:string print function

sprintf(date, "%d/%d/%d", a, b, c); 

,并包括头stdio.h

而且,这样做

char date; 

使得date一个角色,但你希望它是一个字符串。因此在其中分配内存:

char date [10]; 

它使它成为一个字符串或一个包含10个元素的字符数组。但是,您只能存储9个字符,因为您必须为null终止符或\0保留一个元素。


如何sprintf工作?

如果你困惑什么sprintf在做,基本上第一个参数就是sprintf是印刷,第二个参数是要打印的内容,第三,第四,等参数都将被替换的变量由%d%s

为了更好地解释,请参阅this

C库函数sprintf()用于存储格式的数据为字符串。您也可以说sprintf()函数用于使用格式化数据创建字符串作为输出。该sprintf()函数的语法如下:

int sprintf (char *string, const char *form, …); 

您还可以使用itoa,但它不是标准。

+0

非常感谢。有效 ! – Pri