2011-11-20 67 views
0

试图用C语言作为基础,以随机顺序(一副牌)建立一个1-52的数字列表。一切正常,但我所有尝试连接字符串并以失败告终。有什么建议么?注意:这不是我用来创建游戏的作业。Concat LPSTR in C

// 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, ","); 
     } 
    } 

我的最终结果总是乱码文本。谢谢您的帮助。

+0

这不是C++;它是C. – cHao

+0

谢谢,你是对的。更新。 –

+0

C或C++如何对“尽可能泛型”有影响? – Thanatos

回答

1

我们正在编写C++还是C?在C++中,CONCAT-ING一个字符串就是:

string_out = string_a + string_b 

...因为你会使用std::string。此外,如果这是C++,则STL具有std::shuffle函数。

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

+0

对不起,这是C. –

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; 
4

你留着写入“结果”的相同位置。

sprintf不会为你追加。

您可以考虑在每个sprintf之后获取返回值(它是写入的字符数),并将指针增加到结果缓冲区。即是这样的:

(伪代码):

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

我想,如果没有记错,那sprintf的永远写入缓冲区以字节0开始这意味着你会写的第一对夫妇一个字节一遍又一遍地与一个数字,然后一个逗号,然后一个数字。检查你的第一个字节是否是“,[0-9]” - 如果是的话,那是你的问题。