c++ - 如何打印 const 字符数组?

标签 c++ char stringstream

我写了下面的代码,保存在一个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/

相关文章:

c++ - 如何打印子矩阵?

c++ - 什么是 `CString` ?

c# - C#中如何比较字符

java - JAVA char 数组的最后一个元素不被替换

c++ - Ofstream 写入太多字节

c++ - 多线程环境中的 Linux 高分辨率计时器?

c - 如何复制文本直到换行符?

c++ - 通过 stringstream 将数字分配给 char*

C++:如何构建两个空格分隔字符串的交集字符串?

c++ - std::stringstream 如何处理 operator<< 中的 wchar_t*?