How to print 2D Arrays in C++?

前端 未结 3 2028
轮回少年
轮回少年 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 12:54

    It is not only mistake that you miss the "endl". The program will also skip the first line in the source file because of calling the function discard_line(reg), so you only can get the others data(5 6 7 8). It is not necessary to use the function at all. in addition, make sure that you init the array and check boundary of array, such as MAX_SIZE, to guarantee the input data not to overflow the array.

    0 讨论(0)
  • 2020-12-03 13:02

    you can do it like this

    #include <iostream>
    
    int your_array[2][4] = { 
      {1,2,3,4}, 
      {5,6,7,8}  
    };
    
    using namespace std;
    
    int main() {
    
        // get array columns and rows
          int rows =  sizeof your_array / sizeof your_array[0]; 
          int cols = sizeof your_array[0] / sizeof(int); 
          
          // Print 2d Array
         cout << "your_array data "<<endl<<endl;
        for (int i = 0; i < rows; ++i)
        {
            for (int j = 0; j < cols; ++j)
            {
                std::cout << your_array[i][j] << std::endl;
            }
         //   std::cout << std::endl;
        }
    
    }
    

    output

    1
    2
    3
    4
    5
    6
    7
    8
    
    0 讨论(0)
  • 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 <iostream>
    
    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.

    0 讨论(0)
提交回复
热议问题