user1763546
user1763546

Reputation:

Simplest way to count the rows and columns in a matrix

Okay so I am making the game of life in C not C++ because we are not allowed to use the string library and I was just wondering how to count the rows and columns of an arbitrary input file..

And yes this is a homework assignment but this is just the very beginning.. and I am stuck and feel like an idiot.

Here's an example:

00000000100000001010
00000000010000001001
11100000010100000010
10100100101010101010
00101010010010101000

So I need a SIMPLE way to count the rows and columns in an arbitrary file, I guess you would count char by char for columns and line by line for rows but every time I try something like that it just messes up.

So please help me out on this, thanks!

Upvotes: 0

Views: 3663

Answers (3)

Umar Ahmad
Umar Ahmad

Reputation: 410

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
    FILE *fp;
    int row = 0, col = 0;
    char c;
    fp = fopen("file","r+");
    while( (c = fgetc(fp)) != EOF ){
        if(c != '\n' && row == 0){
            col++;
        }
        else if(c == '\n')
            row++;
    }
    row++;  /* If your file doesn't end with a \n */
    printf("Rows = %d\tColumns = %d\n",row,col);
    return 0;
}

Here "file" is your name of the arbitrary input file.
Caution: This code works correctly only when there is no "enter" at the end of file.

Upvotes: 0

LearningC
LearningC

Reputation: 3162

you need to do it in c right. ok first count the number of characters in each line by using somemethod. let len1 be the line length. then use

fseek(fp, 0, SEEK_END);
len2 = ftell(fp);

then len2=len2/(len1+1). add 1 to len1 to consider the newline character at the end of each line and EOF at the last line. then the matrix size is (len1,len2)

Upvotes: 1

lthreed
lthreed

Reputation: 444

Something like this should work

char *matrix; // this is our matrix read in from file

int rows = 0;
int cols = 0;
int tempCols = 0;
int index = 0;

// assumes matrix is a null-terminated string
while (matrix[index] != 0) {
    tempCols++;
    if (matrix[index] == '\n') {
        rows++;
        if (tempCols > cols) {
            // this will return the largest column size if it's not rectangular
            cols = tempCols;
            tempCols = 0;
    }

Upvotes: 0

Related Questions