Finding Number of Columns in Text File

Hi everyone,

I want to print the number of columns in the text file.

My file is

07MWSKN 765 2 34123
07MWZBW 56 197 165
07MWZDW 765 234 123

Every line has same and fixed number of columns which is 4 but the following code gives 1 as an output!

1
2
3
4
5
6
7
8
  ifstream file("DB.txt");
	int val = 0,  cols = 0, numItems = 0;
	while (file.peek() != '\n' && file >> val)
	{
		++numItems;
	}
	cols = numItems;
	cout << cols;


Could you help me out please?

Thanks,
Erdem
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
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
   int rows = 0, cols = 0;
   string line, item;

   ifstream file( "DB.txt" );
   while ( getline( file, line ) )
   {
      rows++;
      if ( rows == 1 )                 // First row only: determine the number of columns
      {
         stringstream ss( line );      // Set up up a stream from this line
         while ( ss >> item ) cols++;  // Each item delineated by spaces adds one to cols
      }

       // .... //                      // Do any processing on a line here

      cout << "Line read is " << line << endl;
   }
   file.close();

   cout << "\nFile had " << rows << " rows and " << cols << " columns" << endl;
}


Line read is 07MWSKN 765 2 34123
Line read is 07MWZBW 56 197 165
Line read is 07MWZDW 765 234 123

File had 3 rows and 4 columns
Thank you very much @lastchance. It works! ;)
Topic archived. No new replies allowed.