如何为sprintf创建可变大小的字符串

时间:2011-02-24 13:08:32

标签: c++

我想像这样制作可变大小的字符串“msg”。

char *msg;
sprintf(msg,"Msg",variable)

我不想使用字符串。 什么是最好的解决方案

2 个答案:

答案 0 :(得分:3)

C字符串是固定大小的。 <string>的大小可变。如果您不想使用string但仍有可变大小,则必须告诉我们您不想使用<string>的原因,或者我们只是告诉您它是 解决您的问题。

也许你根本不知道<string>的方式,也许你只知道sprintf()并意识到你不能用它来写std::string?在这种情况下,我建议并向您呈现<sstream>和C ++输出的operator<<()语法:

#include <iostream>
#include <sstream>
#include <string>

// Using C-style I/O here to make it easier for you.
// You *should* use <iostream> and std::cout instead.
#include <stdio.h>

int main()
{
    int variable = 42;

    // creating a string stream, and writing to it.
    std::ostringstream myStream;
    myStream << "Msg" << variable;

    // extract the string from the string stream
    std::string myString = myStream.str();

    // extract C string from C++ string
    // CAREFUL - the return value is a *temporary* as well as a *constant*.
    printf( "%s\n", myString.c_str() );

    // of course, you can extract the C string directly from the stream
    printf( "%s\n", myStream.str().c_str() );

    // as I said above, in C++ you would use std::cout instead of printf() -
    // and you would not need to extract C style strings anymore.
    std::cout << myString << " - " << myStream.str() << std::endl;

    return 0;
}

如果这不会让您感到痒痒,那么snprintf()可能正是您所寻找的:

#include <stdio.h>

#define MSG_LENGTH 1000

int main()
{
    int variable = 42;
    char msg[ MSG_LENGTH ];
    if ( snprintf( msg, MSG_LENGTH, "Msg%d", variable ) > MSG_LENGTH )
    {
        // your buffer was not large enough
    }
    return 0;
}

snprintf()的附加数字参数确保缓冲区太短时没有超出缓冲区末尾的写入。但那是纯粹的C,你的问题应该被相应标记。

答案 1 :(得分:1)

您无法为sprintf创建可变大小的字符串。 sprintf函数不知道或不关心目标缓冲区(变量)有多大。由调用者决定缓冲区是否足够大以接收结果。尝试这个,你会看到当sprintf在buf1中用完空间时,它会愉快地继续结束并覆盖buf2(至少在VC9和gcc443中)......

#include <stdio.h>

struct Bufs {
   char buf1[7];
   char buf2[7];
};

int main() {
   Bufs bufs;
   sprintf(bufs.buf1, "Hello, World!");
   printf(bufs.buf1);
}