C中的Concat LPSTR

时间:2011-11-20 01:46:13

标签: c concat

尝试使用基本C作为基本C,以随机顺序(卡片组)构建1-52的数字列表。一切正常,但我所有尝试连接字符串并获得结果都失败了。有什么建议?注意:这不是作业,而是我用来制作游戏的东西。

// Locals
    char result[200] = "";  // Result
    int card[52];           // Array of cards
    srand(time(0));         // Initialize seed "randomly"

    // Build
    for (int i=0; i<52; i++) {
        card[i] = i;  // fill the array in order
    }

    // Shuffle cards
    for (int i=0; i<(52-1); i++) {
        int r = i + (rand() % (52-i));
        int temp = card[i]; card[i] = card[r]; card[r] = temp;
    }

    // Build result
    for (int c=0; c<52; c++) {

        // Build
        sprintf(result, "%s%d", result, card[c]);

        // Comma?
        if ( c < 51 )
        {
            sprintf(result, "%s%s", result, ",");
        }
    }

我的最终结果总是乱码。谢谢你的帮助。

4 个答案:

答案 0 :(得分:4)

你一直在写“结果”的相同位置。

sprintf不会为你做补充。

在每个sprintf之后,您可以考虑获取返回值(写入的char数),并将指针递增到结果缓冲区。例如:

(伪代码):

char result[200];
char * outputPtr = result;

for (int c=0; c<52; c++) {

    // Build
    int n = sprintf(outputPtr, "%d%s", card[c], (c<51 ? "," : ""));
    outputPtr += n;
}

答案 1 :(得分:1)

我们是在写C ++还是C?在C ++中,连接字符串只是:

string_out = string_a + string_b

...因为你正在使用std::string

此外,如果这是C ++,则STL具有std::shuffle函数。

如果这是C,请注意你的所有sprintf都没有连接字符串,它们只是覆盖旧值。

答案 2 :(得分:0)

这会在结果字符串中的每个数字之间添加逗号:

 // Get a pointer to the result string
 char* ptr = &result[0];
 for (int c = 0; c < 52; c++) {

    // Add each cards number and increment the pointer to next position
    ptr += sprintf(ptr, "%d", card[c]);

    // Add a separator between each number
    if (c < 51) {
        *ptr++ = ',';
    }
}
// Make sure the result string is null-terminated
*ptr = 0;

答案 3 :(得分:0)

我认为,如果内存服务,sprintf将始终从字节0开始写入缓冲区。这意味着你将用数字反复写入前几个字节,然后是逗号,然后是数字。检查你的第一个字节是否是“,[0-9]” - 如果是,那就是你的问题。

相关问题