cant print a 2d array - c

maybe this is a very easy question but Im confused

For example, my code is named example.c. It takes as an input a txt file, lets say txt.txt . I run the command ./example txt.txt in a terminal (linux).
According to what the user gives me through the file, I create a 2D array.
If the fcontext of the fie is:
+........- , I count the lines (in this example 1) and the elements before the new line, to find the rows of my array. Successfully I count them in my program.
Can you please tell me what i do wrong in the printing of the file into a 2d array?

I cant print the array properly
thanks again!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    #include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
int lines=0, rows=0, j, k;
char ch, array[1000][1000];
FILE *fin;
    if(argc!=2){
        exit(2);
    }
    fin=fopen(argv[1],"r");
    if(fin==NULL) {
        exit(2);
    }
while(!feof(fin)){
        ch=fgetc(fin);
        if(ch=='\n') lines++;
    }
fclose(fin);
fin=fopen(argv[1],"r");
while(!feof(fin)){
        ch=fgetc(fin);
        if(ch=='+' ||ch=='-'|| ch=='.'||ch=='X') rows++;
        if(ch=='\n') break;
    }
printf("%d %d\n", lines, rows);
fclose(fin);
fin=fopen(argv[1],"r");
while(!feof(fin)) {
   for(j=0; j<lines; j++){
        for(k=0; k<rows; k++){
fscanf(fin, "%c", &array[j][k]);
}
 }


//printf("%d %d", lines, rows);
int i;
for(i=0; i<lines; i++){
            for(j=0; j<rows; j++){
              printf("%c", array[i][j]);
//printf("%d %d\n", i, j);

}}
fclose(fin);
return 0;
}
}
Last edited on
Hello maryt,

At first read it looks OK although I do have a concern with while(!feof(fin)). Doing this in C++ code it usually ends up processing the last read twice before the while condition figures out that it has reached "eof".

With out knowing what the input file looks like I have no way of testing the program. Right now all I can do is compile the program and see if there are any errors. Compiling here shows no errors and exits because it can not open the file.

Andy
+X..XX....-
.X..X..X-..
.X.........
...XX......
XXX.+X.....
..X.....XXX
...XXX..X-.
.-.....X...

this is an example of txt input
Last edited on
Hello maryt,

Thank you . I will see what I can come up with.

Andy
Andy thank you very much
I tried a lot and i really cant find the solution.
So i want to change my approach.

Is it possible to write, concerining the same example.

How can i read the context of this file and store it into a 2d array?

I only have these possible inputs and i want to save them correctly in an array.

I also need to know correctly their coordinates in the array

thanks. i have tried a lot and i cant do that correctly with all that bugs.

only these inputs i have:

+.......-


+........-



+..X..X...
....XX...-


+X..XX....-
.X..X..X-..
.X.........
...XX......
XXX.+X.....
..X.....XXX
...XXX..X-.
.-.....X...
Hello maryt,

First question is do you have to do this in C or do you want C++?

Right now I am down to the problem being in the read loop, but I just could not figure it out last night. I will give it a look today.

If you want to do this in C++ it would be a much easier task as I have not done much with C in many years.

One thing I did find with the read is that when finished reading a line you have to add the '\0' at the end of the line. I also shortened the array size for now to make it smaller to work with. This way I can see what is in the array with out all the garbage that is left.

Hope that helps,

Andy
anything that fixes that please :(
Hello maryt,

It is not a whole program, but it does load a 2D char array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <string>
#include <limits>
#include <chrono>
#include <thread>
#include <fstream>

constexpr std::size_t MAXROW{ 20 };  // <--- Change size as needed.
constexpr std::size_t MAXCOL{ 20 };  // <--- Change size as needed.

void ReadFile(std::istream& inFile, char (&aLine)[MAXROW][MAXCOL]);  // <--- The array is being passed by reference.
//  Not necessary, but does help with debugging.

int main()
{
	char ch, aLine[MAXROW][MAXCOL]{};

	std::string iFileName{ "Input.txt" };

	std::ifstream inFile;

	inFile.open(iFileName);

	if (inFile.is_open())
	{
		std::cout << "\n File " << iFileName << " is open" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(2));  // <--- Needs header files chrono" and "thread".
                                                      //  Change 2 to 0 or comment out these two lines when working.
	}
	else
	{
		std::cout << "\n File " << iFileName << " did not open" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread".
		exit(1);
	}

	ReadFile(inFile, aLine);
	
	//  May not need this line. If you have to press enter twice you do not need it.
	//  Uncomment if you do not see the next "cout".
	//std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires heder file <limits>.

	std::cout << "\n\n Press Enter to continue";
	std::cin.get();

	return 0;
}

void ReadFile(std::istream& inFile, char (&aLine)[MAXROW][MAXCOL])
{
	std::string line;
	std::size_t row{}, col{}, index{};

	while (std::getline(inFile, line))
	{
		for (size_t col = 0; col < line.size(); col++)
		{
			aLine[row][col] = line[index++];
		}

		row++;
		index = 0;
	}
}


My biggest problem with your C code was in the loop to load the array. Things are happening that should not happen and I am having trouble figuring it out. Given enough time I would make it work.

Hope that helps,

Andy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

//======================================================================

class Game
{
   vector<string> board;
   int rows = 0;
   int cols = 0;
public:
   Game() {}
   Game( int r, int c );
   void size( int &r, int &c ) { r = rows; c = cols; }
   bool input( istream &strm );
   bool output( ostream &strm );
   bool get( int r, int c, char &symbol );
   bool put( int r, int c, char symbol );
};

//--------------------------------------

Game::Game( int r, int c )
{
   rows = r;
   cols = c;
   board = vector<string>( rows, string( cols, '.' ));
}

//--------------------------------------

bool Game::input( istream &strm )
{
   if ( !strm ) return false;

   board.clear();
   string line;
   while( getline( strm, line ) ) board.push_back( line );

   rows = board.size();
   cols = board[0].size();

   return ( rows >= 1 && cols >= 1 );
}

//--------------------------------------

bool Game::output( ostream &strm )
{
   if ( !strm ) return false;

   for ( string line : board ) strm << line << '\n';
   strm << '\n';

   return ( rows >= 1 && cols >= 1 );
}

//--------------------------------------

bool Game::get( int r, int c, char &symbol )
{
   if ( r < 0 || r >= rows || c < 0 || c >= cols ) 
   {
      symbol = '?';
      return false;
   }
   else
   {
      symbol = board[r][c];
      return true;
   }
}

//--------------------------------------

bool Game::put( int r, int c, char symbol )
{
   if ( r < 0 || r >= rows || c < 0 || c >= cols ) return false;
   board[r][c] = symbol;
   return true;
}

//======================================================================

int main()
{
   ifstream in( "data.dat" );

   Game G;
   G.input( in );
   G.output( cout );

   Game H( 5, 5 );
   H.output( cout );
}

//====================================================================== 


data.dat:
+X..XX....-
.X..X..X-..
.X.........
...XX......
XXX.+X.....
..X.....XXX
...XXX..X-.
.-.....X...


Output:
+X..XX....-
.X..X..X-..
.X.........
...XX......
XXX.+X.....
..X.....XXX
...XXX..X-.
.-.....X...

.....
.....
.....
.....
.....
Topic archived. No new replies allowed.