2011-09-21 53 views
0

HI我有以下三個字符串,上面的代碼如何用字符串中的數據替換訪問說明符?

char* string1, string2, string3; 
printf("First string = %s", string1); 
printf("Second string = %s", string2); 
printf("Third string = %s", string3); 

輸出是,

First string = My Content is : %s, My value is : %d 
Second string = Open source OS 
Thirf string = 100 

現在我需要在%S &%d simultaneousaly的地方合併字符串2和STRING3內容,所以我應該得到以下字符串,

My Content is : Open source OS 
My value is : 100 

任何人都可以建議我如何將上述兩個字符串添加到另一個字符串。 在此先感謝。

+0

您可以指定字符串1,字符串和STRING3在代碼中更精巧? –

+0

沒有人注意到。但是你只有一個字符串'string1'和兩個char變量。 'string2'和'string3'實際上只是字符。因此第二個第三個printf()語句是無效的。因此,他們爲什麼工作是一個完全的謎,或者你已經犯了一個錯誤的粘貼錯誤。 –

回答

1

使用sprintfprintf沿:

char format[1024]; 
sprintf(format, "First string = %s", string1); //this makes the format string 
printf(format, value1, value2); //this prints output with the formatted string 
+0

謝謝納瓦茲,你能告訴我什麼是格式?我試圖通過使用char *,但它沒有給出預期的結果。 – BSalunke

+0

@BSalunke:'format'被聲明爲'char format [1024]'。注意到那個? – Nawaz

+1

非常感謝,它與你的解決方案很好地工作。 – BSalunke

2

嘗試:

printf(string1, string2, atoi(string3)); 
+1

嗨伊蘭,不,它不工作。你有沒有其他解決方案? – BSalunke