How to print 2D Arrays in C++?

前端 未结 3 2039
轮回少年
轮回少年 2020-12-03 12:23

I am trying to print a text file out on screen using arrays, but I\'m not sure why it does not appear the way it is in the text file.

The text file:

         


        
3条回答
  •  隐瞒了意图╮
    2020-12-03 13:14

    You are printing std::endl after each number. If you want to have 1 row per line, then you should print std::endl after each row. Example:

    #include 
    
    int main(void)
    {
        int myArray[][4] = { {1,2,3,4}, {5,6,7,8} };
        int width = 4, height = 2;
    
        for (int i = 0; i < height; ++i)
        {
            for (int j = 0; j < width; ++j)
            {
                std::cout << myArray[i][j] << ' ';
            }
            std::cout << std::endl;
        }
    }
    

    Also note that writing using namespace std; at the beginning of your files is considered bad practice since it causes some of user-defined names (of types, functions, etc.) to become ambiguous. If you want to avoid exhausting prefixing with std::, use using namespace std; within small scopes so that other functions and other files are not affected.

提交回复
热议问题