簡體   English   中英

在C中串聯char字符串

[英]Concatenating char string in C

我搜尋了互聯網無濟於事。 我不明白這個問題在問什么。

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中運行代碼時,我得到的funcmac解決方案分別為1和1。 當我打印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函數復制到char字符串actualResult但不知道如何正確執行。

任何幫助表示贊賞。

非常簡單:使用“ 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM