Bash不会将字符串拆分为超过第一个索引的数组

时间:2018-01-18 18:23:03

标签: arrays string bash split

我有一个变量设置为当前工作目录中的所有子目录,我这样做了

void Level::printgrid(int level)
{
sf::RenderWindow window(sf::VideoMode(800, 600), "Game On");
sf::Font MyFont;

if (!MyFont.loadFromFile("tnr.ttf"))
{
    // Error...
}

ifstream my_file("nn.txt"); //text that i will be reading from 
char number;   

int i = 0; //to help loop
int j = 0;

while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
        else
        {
            window.clear();
            while (i<row) // ive tried 2 for loops that didnt work cause
            {             // it kept re-entering those loops 
                while (j<col)
                {
                    my_file.get(grid[i][j]); //getting the chars one by one
                    cout << grid[i][j];  // printing them on terminal 
                                         //so i can check its correct
                    //changing to text that is drawable to print in window  
                    sf::Text text(grid[i][j], MyFont, 30);
                    text.setPosition(0 + (30 * i), 0 + (30 * j));
                      // drawing it in window
                    window.draw(text);
                    window.display();
                    j++;
                }
                my_file.get(number);
                cout << endl;
                i++;
                j = 0;
            }
        }
    }

  }
 }

这会将以下内容返回给我&#34; d1 / d2 /&#34;我想通过空格将它拆分成一个数组,所以我运行下面的代码,我发现堆栈溢出似乎适用于其他人,但不适合我。代码是

directories=` ls -d -- */`

现在这应该将我的字符串拆分为两个索引grArray [0]和grArray [1],它应该是&#34; d1 /&#34;和&#34; d2 /&#34;分别,但当我尝试打印数组的两个索引时,我得到&#34; d1 /&#34;并且第二个阵列出现为&#34; &#34;

如果有人能够指出我在这里失踪的东西,我会非常感激。谢谢。

1 个答案:

答案 0 :(得分:5)

不要像这样使用ls;只需使用glob直接设置数组:

directories=( */ )