如何打印const chars数组?

时间:2014-05-12 21:36:25

标签: c++ char stringstream

我编写了以下代码以保存在char *数组中并打印以下内容: band1.txt band2.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

这怎么可能?

编辑:其实我希望“band”为char *,以便调用想要这样一个参数的ifstream current_band_file(current_band)构造函数

4 个答案:

答案 0 :(得分:4)

通过使用指向已销毁对象的指针,您有未定义的行为。

只是不要使用原始指针和原始数组等等。

std::string是你的朋友的字符串,std::vector是你的数组朋友。


示例:

#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;
    }
}

答案 1 :(得分:1)

作为对现有代码的最小更改,您可以更改:

current_band[i] = str.c_str();

为:

strcpy(current_band[i], str.c_str());

然而,从混合的C和C ++转向更惯用的C ++(比如Cheers和hth。 - Alf的回答)将为你的未来提供更好的服务。

使用char[11]std::string之类的内容意味着您一直坚持:

  • 最大长度11的任意选择,即使可能没有这个限制的良好技术原因。
  • 处理正确的C ++实现隐藏的内存分配的所有细节。
  • 阅读低级代码风格的自然要少得多。

答案 2 :(得分:0)

作为创可贴,您可以替换:

current_band[i] = str.c_str();

if ( str.size() >= 11 )
    throw std::runtime_error("string too long");
std::strcpy(current_band[i], str.c_str());

然而,用以下内容替换整个事情会更好:

std::vector<std::string> current_band(103);
int i = 0;
for (auto &s : current_band)
{
    // your sstm stuff, storing to s
}

答案 3 :(得分:0)

这是一种更加健壮,可读且更可能正确的替代方式。

#include <vector>
#include <iostream>
#include <string>
#include <sstream>

using namespace std;


int main()
{
    vector<string> bands;
    bands.reserve(103);
    for(size_t i = 1 ; i <= 103 ; ++i) {
        ostringstream ss;
        ss << "band" << i;
        bands.emplace_back( ss.str() );
    }

    for (size_t index = 0 ; index < bands.size() ; ++index) {
        cout << index << " : " << bands[index] << endl;
    }

    return 0;
}

输出:

Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1

Executing the program....
$demo 
0 : band1
1 : band2
2 : band3
...
100 : band101
101 : band102
102 : band103