我有一个程序使用to_string
转换一个int
to a string
,然后使用将其转换为 C 字符串string::c_str()
,它存储在一个数组中const char*
。当程序输出每个const char*
,结果并不出乎我的意料。对于下面的示例程序,它输出一个计数器和一个不变的变量,我希望输出由计数器组成,后跟不变的数量,然后用星号分隔:
1
10
***************
2
10
****************
3
10
*****************
…
每次循环迭代始终输出相同的值(恰好是不变变量的值),而不是向上计数:
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
10
10
**************
用于生成上述内容的示例程序:
#include <iostream>
#include <string>
using namespace std;
int main() {
int order = 1;
for (int i = 1; i < 10; ++i, ++order) {
const char* a[2];
int b = 10;
a[0] = to_string(order).c_str(); // these
a[1] = to_string(b).c_str(); // are the
cout << a[0] << endl; // relevant
cout << a[1] << endl; // lines
cout << "**************" << endl;
}
}
错误在哪里?是不是因为数组元素有const char *
type?
在这一行
a[0] = to_string(order).c_str();
to_string(order)
生成一个临时字符串。的结果c_str()
仅当临时字符串存在时才有效,但语句执行后临时字符串将被销毁。a[0]
然后留下一个无效的指针。
要解决这个问题,您需要将字符串存储在某个地方,这样它们就不会立即消失:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int order=1;
for(int i=1; i<10;++i,++order){
const char* a[2];
int b = 10;
auto order_str = to_string(order);
auto b_str = to_string(b);
a[0] = order_str.c_str();
a[1] = b_str.c_str();
cout << a[0] << endl;
cout << a[1] << endl;
cout << "**************" << endl;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)