如何在 C 中打印二维数组?

新手上路,请多包涵

我正在尝试使用数组在屏幕上打印一个文本文件,但我不确定它为什么不像文本文件中那样显示。

文本文件:

 1 2 3 4
5 6 7 8

应用丢弃功能后屏幕显示如下:

 1
2
3
4
5
6
7
8

编码:

 #include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>

using namespace std;

const int MAX_SIZE = 20;
const int TOTAL_AID = 4;

void discard_line(ifstream &in);
void print(int print[][4] , int size);

int main()
{
    //string evnt_id[MAX_SIZE]; //stores event id
    int athlete_id[MAX_SIZE][TOTAL_AID]; //stores columns for athelete id
    int total_records;
    char c;
    ifstream reg;
    reg.open("C:\\result.txt");

    discard_line(reg);
    total_records = 0;

    while( !reg.eof() )
    {
        for (int i = 0; i < TOTAL_AID; i++)
        {
            reg >> athlete_id[total_records][i] ;//read aid coloumns
        }
        total_records++;
        reg.get(c);
    }

    reg.close();

    print(athlete_id, total_records);

    system("pause");
    return 0;
}

void discard_line(ifstream &in)
{
    char c;

    do
        in.get(c);
    while (c!='\n');
}

void print(int print[][4] , int size)
{
    cout << " \tID \t AID " << endl;
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < TOTAL_AID; j++)
        {
            cout << print[i][j] << endl;
        }
    }
}

原文由 Nick 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 394
1 个回答

你可以这样做

#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;
    }

}

输出

1
2
3
4
5
6
7
8

原文由 user889030 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题