我写了下面的代码,保存在一个char *数组中,打印如下内容: 带1.txt 带2.txt ... band3.txt 代码似乎是正确的,但控制台上打印的内容很奇怪。
代码:
const char ** current_band = new const char * [103];
stringstream sstm;
string str;
for (i=0;i<103;i++){
current_band[i] = new char[11];
}
for (i=0;i<103;i++){
sstm.str("");
sstm << "band" << i+1 << ".txt";
str = sstm.str();
current_band[i] = str.c_str();
cout << current_band[i] << endl;
cout << i << endl;
}
for (i=0;i<103;i++){
cout << current_band[i] << endl;
cout << i << endl;
}
控制台:
band1.txt
0
band2.txt
1
...
band103.txt
102
然后是最后一个循环:
band103.txt
0
band102.txt
1
band103.txt
2
band102.txt
3
...
band102.txt
101
band103.txt
102
这怎么可能?
编辑:实际上我希望“带”是 char* 以便调用需要这样一个参数的 ifstream current_band_file(current_band) 构造函数
最佳答案
通过使用指向已销毁对象的指针,您有未定义的行为。
只是暂时不要使用原始指针和原始数组之类的东西。
std::string
是字符串的 friend ,std::vector
是数组的 friend 。
例子:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
auto main()
-> int
{
vector<string> band_names;
for( int i = 1; i <= 103; ++i )
{
band_names.push_back( "band" + to_string( i ) );
}
for( string const& name : band_names )
{
cout << name << endl;
}
}
关于c++ - 如何打印 const 字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23619289/