如何在C++中打印2D数组?

Nic*_*ick 6 c++ arrays revision multidimensional-array

我试图使用数组在屏幕上打印文本文件,但我不确定为什么它不会出现在文本文件中.

文本文件:

1 2 3 4
5 6 7 8
Run Code Online (Sandbox Code Playgroud)

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

1
2
3
4
5
6
7
8
Run Code Online (Sandbox Code Playgroud)

代码:

#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;
        }           
    }
}    
Run Code Online (Sandbox Code Playgroud)

Lih*_*ihO 13

std::endl在每个号码后打印.如果你想每行有1行,那么你应该std::endl在每行之后打印.例:

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,using namespace std;在文件开头写入被认为是不好的做法,因为它会导致一些用户定义的名称(类型,函数等)变得模糊不清.如果您想避免std::使用前缀,请using namespace std;在小范围内使用,以便其他功能和其他文件不受影响.

  • 当使用cpp文件而不是标题时,"using namespace std"并不是那么糟糕. (3认同)