2014-10-20 35 views
-7

我不能在这些字符串中串入字符串。无法在c中连接int和字符串

代码

void main 
{ 
    char buffer[10]; 
    int degrees=9; 
    sprintf(buffer,"%d",degrees); 
    string completeMessage=(("turnAnticlockwise(%s);",buffer)); 
    printf(completeMessage); 
} 

任何帮助将是要命!

+2

C不具有“字符串'类型。事实上,它根本没有任何理智的字符串类型。 – 2014-10-20 15:35:10

+4

欢迎来到StackOverflow!请*复制*从您的源代码,从不*重新键入*您的代码在这里。错别字,就像在main()中省略你的parens一样,总是在蠕变。 – 2014-10-20 15:35:20

+5

为什么不'sprintf(completeMessage,“turnAnticlockwise(%d);”,度)'? – 2014-10-20 15:35:24

回答

4

也许你想这样的:

#include <stdio.h> 

void main() 
{ 
    char buffer[30]; // note it's 30 now, with 10 the buffer will overflow 
    int degrees=9; 
    sprintf(buffer, "turnAnticlockwise(%d)",degrees); 
    printf("%s", buffer); 
} 

这个小程序将输出:

turnAnticlockwise(9) 
1

看到: http://www.cesarkallas.net/arquivos/faculdade/estrutura_dados_1/complementos%20angela/string/conversao.html 具体如下:

#include <stdio.h> 

int main() { 
    char str[10]; /* MUST be big enough to hold all 
        the characters of your number!! */ 
    int i; 

    i = sprintf(str, "%o", 15); 
    printf("15 in octal is %s\n", str); 
    printf("sprintf returns: %d\n\n", i); 

    i = sprintf(str, "%d", 15); 
    printf("15 in decimal is %s\n", str); 
    printf("sprintf returns: %d\n\n", i); 

    i = sprintf(str, "%x", 15); 
    printf("15 in hex is %s\n",  str); 
    printf("sprintf returns: %d\n\n", i); 

    i = sprintf(str, "%f", 15.05); 
    printf("15.05 as a string is %s\n", str); 
    printf("sprintf returns: %d\n\n", i); 

    return 0; 
}