填充字符串数组或char *数组的问题

时间:2015-03-20 08:16:21

标签: c++ arrays string

非常基本的C ++问题。看起来我真的生锈了... 我想做的就是从文件中读取一个X字符串数组,并创建一个水平字符串的X垂直字符串数组。
IE:
文件包含:

azert
qsdfg
wxcvb
poiuy
mlkjh

我想创建一个包含以下内容的字符串数组:

aqwpm
zsxol
edcol
rfvuj
tgbyh

这是我到目前为止所尝试的内容:

[bad code]
const int SIZE = 37;
    std::string table_h[SIZE];
    std::string table_v[SIZE];

int i = 0;
    while (source >> table_h[i])    //,sizeof    table_h[i]
    {
        for (int j = 0; j< SIZE; j++)
        {
            table_v[j][i] = table_h[i][j];
        }
        i++;
    }

- &GT;适用于第一行,当i = 1时中断。我不明白。 我注意到虽然table_v[0][0] = 'f';工作得很好。 table_v[0][36] = 'f';table_h[0].at(36);都会中断。

char *(这是我的第一个想法),

char * table_h[SIZE];
char * table_v[SIZE];

类似

table_v[0][0] = 'f';

立即休息。 我想我需要先分配内存或初始化一些东西?

提前谢谢。

3 个答案:

答案 0 :(得分:1)

确实table_v[j]是一个空字符串。

字符串需要为字符分配空间。这不是由索引运营商完成的,即

table_v[j][9] = 'a';

假设为table_v[j]分配了足够的空间。

您可以对字符串append添加到最初为空的字符串。 Append不会使用chars,因此您可以使用table_h[i][j]而不是使用substr索引。

std::string to_append = table_j[i].substr(j, 1)
table[j].append(to_append);

这也让您免除i计数器。

答案 1 :(得分:1)

在使用operator []访问字符串之前,您应该设置字符串的大小。调整table_h的大小是可选的,但您必须调整table_v的大小。

    const int SIZE = 37;
    std::string table_h[SIZE];
    std::string table_v[SIZE];

    for (size_t i = 0; i < SIZE; ++i)
    {
        table_h[i].resize(SIZE);
        table_v[i].resize(SIZE);
    }

    int i = 0;
    while (source >> table_h[i])
    {
        for (int j = 0; j < SIZE; j++)
        {
            table_v[j][i] = table_h[i][j];
        }
        i++;
    }

请参阅working example

在我看来,如果你知道字符串的大小,调整大小比附加更好。它可以节省一些内存重新分配,而恕我直言,这只是更好的解决方案。

答案 2 :(得分:0)

这是一个演示程序,展示了如何完成

#include <iostream>
#include <vector>
#include <string>
#include <numeric>

int main() 
{
    std::vector<std::string> v1 = 
    { 
        "azert", "qsdfg", "wxcvb", "poiuy", "mlkjh"
    };

    for ( const std::string &s : v1 ) std::cout << s << ' ';
    std::cout << std::endl;

    auto max_size = std::accumulate( v1.begin(), v1.end(), 
                                     size_t( 0 ),
                                     []( size_t acc, const std::string &s ) 
                                     {
                                        return acc < s.size() ? s.size() : acc;
                                     } );

    std::vector<std::string> v2( max_size );

    for ( const std::string &s : v1 )
    {
        for ( std::string::size_type i = 0; i < s.size(); i++ )
        {
            v2[i].push_back( s[i] );
        }
    }

    for ( const std::string &s : v2 ) std::cout << s << ' ';
    std::cout << std::endl;

    return 0;
}

程序输出

azert qsdfg wxcvb poiuy mlkjh 
aqwpm zsxol edcik rfvuj tgbyh 

至于你的代码而不是这些陈述

std::string table_h[SIZE];
std::string table_v[SIZE];

定义了两个空字符串数组。所以你可能不会将下标opertaor应用于空字符串。您可以使用例如成员函数push_back

    for (int j = 0; j< SIZE; j++)
    {
        table_v[j].push_back( table_h[i][j] ); 
    }
相关问题