2014-10-20 69 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; 
}