我想像这样制作可变大小的字符串“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/