c++ - 如何为 sprintf 制作可变大小的字符串

标签 c++

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

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

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

最佳答案

C 字符串是固定大小的。 <string>是可变大小。如果你不想使用 string但仍然有可变大小,您必须告诉我们为什么您不想使用 <string> ,否则我们只会告诉您它是您问题的解决方案。

也许您只是不知道如何绕过<string> ,也许你只知道sprintf()并意识到你不能用它来写入 std::string ?既然如此,我推荐并呈现给你<sstream>operator<<() C++输出语法:

#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,你的问题应该被相应地标记。

关于c++ - 如何为 sprintf 制作可变大小的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5105089/

相关文章:

c++ - Qt添加 "action"到动态添加的QWidget

c++ - Cout 没有打印出预期的结果

c++ - 提升asio跨平台换行困惑

c++ - shared_ptr 和 weak_ptr 的区别

c++ - QNetworkAccessManager问题

c++ - address of operator 可以初始化一个指针但是填充的值是垃圾

c++ - 如何让编译器在 C++ 中创建默认构造函数?

c++ - 可变参数模板类参数容器实例化

c++ - 没有明确声明的 int[] 中的 foreach

c++ - Visual Studio 未加载符号