2015-09-06 92 views
0

我已經搜索了互聯網無濟於事。我不明白這個問題在問什麼。在C中串聯char字符串

void case_three(int x, int y, char *actualResult) { 
    int i, j, s, t, p, q; 

    s = i = x; // initialize variables with value from x 
    t = j = y; // initialize variables with value from y 
    p = func(++i, ++j); 
    q = mac(++s, ++t); 
       // Copy the output to actualResult below... 
    printf("\n\n");             //first variable increment 
    printf("Q3: Result from func(x, y) = %d and mac(x, y) = %d.", p, q); 

    // Replace the quoted content in the following strcpy statement with the actual output from last printf statement above. 
    // Do not alter the text or add any spaces to it. 
    strcpy(actualResult, "Q3: Result from func(x, y) = %d and mac(x, y) = %d", p, q); 
    printf("\n\n"); 
    printf(actualResult); 
} 

當我運行在VS的代碼,我得到1和1對funcmac解決方案。當我打印actualResult字符串時,每當我執行它時,我都會收到巨大的數字。另外,當我嘗試在gcc中編譯時,我得到error: too many arguments to function strcpystrcpy(actualResult, "Q3: Result from func(x, y) = %d and mac(x, y) = %d", p, q);行。

所以,我需要將printf函數的輸出複製到字符串actualResult,但不知道如何正確執行。

任何幫助表示讚賞。

回答

2

非常簡單:使用"sprintf()"而不是「printf()」來格式化輸出爲字符串。

你不需要「strcpy()」,而你不能使用帶格式化命令的strcpy。

例:

/* The exact same output will go to your terminal as to the string "actualResult" */ 
printf("Q3: Result from func(x, y) = %d and mac(x, y) = %d.", p, q); 
sprintf(actualResult, "Q3: Result from func(x, y) = %d and mac(x, y) = %d.", p, q); 
+0

完美,謝謝。我正在閱讀說明,說我必須使用「strcpy」,並且無法使其工作。 – corporateWhore

+1

建議養成使用snprintf()的習慣以避免意外的緩衝區溢出。這裏的關鍵詞是「意外的」。 – Gilbert

+1

從閱讀評論中的說明,我會認爲你需要運行該程序,從最後一個printf()獲得輸出,然後用打印的內容替換strcpy的引用部分。例如,如果輸出是「這是輸出」,那麼你可以改變字符串拷貝來讀取:'strcpy(actualresult,「這是輸出」);',這樣來自最後一個printf的輸出將是相同的(可能用於某些自動分級機制)。然而,正如你用gcc所看到的那樣,我懷疑在問題中顯示了'strcpy'中的拼寫錯誤 - 請教你的老師 – thurizas