-4

I have these types of data in txt files.

1   3   4   5
2   4   5   2
3   5   7   8
2   5   7   8

or even

1 3 4 5
2 4 5 2
3 5 7 8
2 5 7 8

Separated with TABs, with one space or exported from excel. I need a function to count columns, that returns an int, how can I do this?

Thanks!

4 Answers4

1

Maybe there is some more elegant way, but you can try something like this:

ifstream file("MyFile.txt"); //open your file
string line;
getline(file, line);         //read the first line of your file to string
stringstream s;
s << line;                   //send the line to the stringstream object...

int how_many_columns = 0;    
double value;

while(s >> value) how_many_columns++;  //while there's something in the line, increase the number of columns

cout << how_many_columns;
plik.close();

It works if the numbers are separated by tab or spaces (also if they are mixed or there are e.g. sometimes two spaces between two numbers). It doesn't work, however, if there's comma between the numbers in the same line.

mks
  • 76
  • 4
0

You can read a line a time, then split space get the number of columns of every line, last output the max number.

0

Short answer

There doesn't exist a native C++ function that would satisfy your needs.

A simple workaround

Assuming that each row contains the same amount of columns and columns can't be empty, one simple possibility would be to walk through the string of the first row and check each character if it matches ' ' or '\t' and then increment a counter unless the previous character was also a space character (i.e. multiple space characters were used to delimit a column)

Please note: This assumes additionally that there exists at least one column in the row and the line does not end with delimiters.

int countColumns(string row){
    int  numberOfColumns=1;
    bool previousWasSpace=false;

    for(int i=0; i<row.size(); i++){
        if(row[i] == ' ' || row[i] == '\t'){
            if(!previousWasSpace)
                numberOfColumns++;

            previousWasSpace = true;
        } else {
            previousWasSpace = false;
        }   
    }   

    return numberOfColumns;
}

Example

Calling

cout << countColumns("1      2 3    4") << endl;
cout << countColumns("1  2  3  4\t\t5") << endl;

returns

4
5
0xpentix
  • 732
  • 9
  • 22
0

This works for a first try. Maybe you want to add some boilerplate to handle some special cases.

int read_columns(I stream& stream){
  int count(0);
  for(char ch; stream.get(ch) && ch != ā€˜\n’; ){
    stream.putback(ch);
    If(int tmp; stream >> tmp) ++count;
  }
  if(stream.bad() || stream.fail()){
    throw exception();
  }
  return count;
}