[英]Unexpected behavior concatenating string
I am trying to concatenate two strings in C++11 and I am often getting an unexpected behavior.我试图在 C++11 中连接两个字符串,但我经常遇到意外行为。
First, I have a function that converts any type to string:首先,我有一个 function 可以将任何类型转换为字符串:
template <class T>
static inline const char * toStr(T arg) {
stringstream ss;
ss << arg;
return (ss.str()).c_str();
}
Then, I use this function like this:然后,我像这样使用这个 function:
string measure_name;
for (unsigned long j = 0; j < 1280; j++) {
measure_name = string("ADC_") + toStr(j);
cout << measure_name << endl;
}
Everything goes well untill I reach a 4 digit number (> 999): my variable measure_name
often equals to "ADC_ADC_"... and it happens randomly.一切顺利,直到我达到一个 4 位数(> 999):我的变量measure_name
通常等于“ADC_ADC_”......它是随机发生的。 I did some research and found nothing about this strange behavior.我做了一些研究,并没有发现这种奇怪的行为。
For your information, this issue is fixed if toStr
returns a string
and not a const char *
.供您参考,如果toStr
返回string
而不是const char *
,则此问题已得到解决。
Also, if I try to print the returned value, I never see it equal to "ADC_ADC_", so I believe the real issue comes from the concatenating instruction:另外,如果我尝试打印返回的值,我永远不会看到它等于“ADC_ADC_”,所以我相信真正的问题来自连接指令:
string measure_name;
for (unsigned long j = 0; j < 1280; j++) {
const char* tmp = toStr(j);
if (!strcmp(toStr(j), "ADC_ADC_"))
cout << "bug" << endl; //never happens
measure_name = string("ADC_") + tmp; //problem comes from here
cout << measure_name << endl;
}
I just wanted to understand what I am doing wrong there... I know I am using very old C++ but it should work anyway.我只是想了解我在那里做错了什么......我知道我使用的是非常旧的 C++ 但无论如何它应该可以工作。
Thank's for your help.谢谢你的帮助。
Here这里
return (ss.str()).c_str();
You are returning a pointer to the buffer of a temporary std::string
(returned from str()
).您正在返回一个指向临时std::string
缓冲区的指针(从str()
返回)。 The pointer returned from the function is useless for the caller, because the std::string
it points to is already gone.从 function 返回的指针对调用者来说是无用的,因为它指向的std::string
已经消失了。
A pointer is just a pointer.指针只是一个指针。 If you want a string, return a std::string
.如果你想要一个字符串,返回一个std::string
。 If you want to return a const char*
then you need to store the string somewhere and manage its lifetime.如果要返回const char*
,则需要将字符串存储在某处并管理其生命周期。
std::string
does mangage the lifetime of a character array, so just do: std::string
确实管理字符数组的生命周期,所以只需:
template <class T>
static inline std::string toStr(T arg) {
stringstream ss;
ss << arg;
return ss.str();
}
If someone needs a c-array of char
they can still call c_str
(and use it as long as the std::string
is still alive).如果有人需要一个char
的 c 数组,他们仍然可以调用c_str
(只要std::string
还活着就可以使用它)。
Instead of your toStr
consider to usestd::to_string
.而不是你的toStr
考虑使用std::to_string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.