How to print 2D arrays in C ++?

I am trying to print a text file on the screen using arrays, but I am not sure why it is not displayed like in a text file.

Text file:

1 2 3 4 5 6 7 8 

It is displayed on the screen as follows after applying the drop function:

 1 2 3 4 5 6 7 8 

Code:

 #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; } } } 
+4
source share
2 answers

You print std::endl after each number. If you want to have 1 line per line, then you should print std::endl after each line. 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 the record using namespace std; at the beginning of your files is considered bad practice, as some user names (types, functions, etc.) become ambiguous. If you want to avoid an exhaustive prefix with std:: use using namespace std; in small areas so as not to affect other functions and other files.

+12
source

Not only the error you miss "endl". The program will also skip the first line in the source file due to calling the discard_line (reg) function, so you can only get the rest of the data (5 6 7 8). There is no need to use this function at all. Also, make sure you initialize the array and check the border of the array, such as MAX_SIZE, to ensure that the input does not overflow the array.

+1
source

Source: https://habr.com/ru/post/1432848/


All Articles