Find the number of columns

Hi,

I have a file called 'file.dat'. This is a text file that have an ASCII matrix

1 2 3
4 5 6
7 8 9

How can a find the number of columns and lines?

It will be wonderful if someone can reply only with C++ high level code(not the old C, please.). But a reply with C code will be appreciated too.

I am using Netbeans 6.5.1 at a Linux Slackware 12 machine.
You really should try coding yourself. We'll help out, but we're not going to write code for you.
I will use
char * fgets ( char * str, int num, FILE * stream ) ;
to do this

1/ count how many space in 1 str.. then you know the column
2/ use loop to count how many str you get ( loop is stopped when str=eof) .. each str you get is a line..



@cstrieder: write your idea, then code it.. if it's wrong, post here.. everyone will solve the problem for you.. ... nobody write code for you
Last edited on
Hi kbw,

I coded some part, to find the number of lines...

1
2
3
4
5
6
7
    int c = 0;
    string line;
    while(!iFile.eof()) {
        getline (iFile, line);
        c++;
    }
    cout << "NĂºmero de linhas: " << c+1 << endl;


But to find the number of columns in a dat file I do not know.

Your help will be appreciated.
That will give the number of lines.

To get the columns you can do pretty much the same. Rather than use an std::ifstream, you make up a std::istringstream and initialise it with the line. Then you can use the same loop to read the content of the line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>
#include <string>

int main()
{
        std::string line = "12 14 16 18 20 24";

        std::stringstream is(line);
        int n;
        while (is >> n)
                std::cout << n << std::endl;

        return 0;
}
Topic archived. No new replies allowed.