简体   繁体   中英

Concatenating char string in C

I've scoured the internet to no avail. I do not understand what this question is asking.

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);
}

When I run the code in VS I get 1 and 1 for the func and mac solutions. When I print the actualResult string, I get HUGE numbers that change everytime I execute it. In addition, when I attempt to compile in gcc, I get a error: too many arguments to function strcpy at the strcpy(actualResult, "Q3: Result from func(x, y) = %d and mac(x, y) = %d", p, q); line.

So, I need to copy the output from the printf function to the char string actualResult but don't know how to do it correctly.

Any help is appreciated.

Very simple: use "sprintf()" instead of "printf()" to do formatted output to a string.

You don't need "strcpy()", and you can't use strcpy with formatting commands.

EXAMPLE:

/* 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM