首页 文章

从文件中打印出2d数组

提问于
浏览
-2

如何以2D阵列的形式将此文本文件打印到控制台窗口 .

maze

我写了这段代码,但它似乎忽略了空格作为字符 .

ifstream mazefile("maze.txt");

char maz[21][31] = {};

int i, j;

for (i = 0; i < 21; i++)
{
    for (j = 0; j < 31; j++)
    {
        mazefile >> maz[i][j];
        cout << maz[i][j];
    }
    cout << endl;
}

1 回答

  • 2

    默认情况下, std::istream::operator<<() 会跳过所有空格(空格,制表符,换行符) . 由于您需要空格,因此应考虑使用 istream::get()istream::getline() .

    选择下面的一个开始,请注意您可能需要使用 get 手动处理换行符 .

    mazfile.get(maz[i][j]);
    mazfile.get();  // Trailing newline
    
    mazfile.get(maz[i], 30);
    mazfile.get();  // Trailing newline
    
    mazfile.get(maz[i], 30, '\n');  // With newline as delimiter
    mazfile.get();  // Trailing newline
    
    mazfile.getline(maz[i]);
    

    或者,您可以强制空格 not 被跳过:

    mazfile >> noskipws >> maz[i][j];
    

相关问题