在C中连接char字符串

时间:2015-09-06 01:29:18

标签: 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 strcpy行获得strcpy(actualResult, "Q3: Result from func(x, y) = %d and mac(x, y) = %d", p, q);

因此,我需要将printf函数的输出复制到char字符串actualResult,但不知道如何正确执行。

感谢任何帮助。

1 个答案:

答案 0 :(得分: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);