2

My task is to count the amount of integers in every line from a txt file in C++.

The file format is :

    Steve Road_43 St43 32 45 2 5 7 23 545

    John Road_21 Dt_4 3 4 5 12 31 0

Finally the format is < string string string int int int int.....int> The problem is that the amount of integers in every line is different, so how can i know the amount of integers in every line ?

My code ->

#include <iostream>
#include <fstream>
#include <sstream>
#include <ctype.h>
#include <string>


using namespace std ;




int main()
{

  string File_Name ,
         temp ;



  int counter_0 = 0 ;



  cout << " Please enter the File-Name :  " ;
  getline ( cin, File_Name ) ;
  cout << endl << endl << endl ;


  ifstream FP_1 ( File_Name ) ;


  if ( FP_1.is_open(  ) )
  {

      while ( ! FP_1.eof( ) )
      {

        getline ( FP_1, temp ) ;
        cout << temp;
        stringstream str ( temp ) ;

         int x ;

         while ( str >> x )              
         {
            counter_0 ++ ;
         }

        cout << " "  << counter_0 <<endl;
        counter_0 = 0;

      }

  }
  else
  {
      exit ( 1 ) ;
  }


  FP_1.close ( ) ;



 system ( " pause " ) ;
 }

counter_0 is always zero..does not count integers

1 Answers1

2

As soon str >> x sees a non int type in the input the state of str is set to fail and you never resume it.

Hence no numbers will be read, since the lines start with non numeric values.

You can consume the two non int values beforehand and read all of the int values afterwards:

     int x ;
     std::string dummy;

     str >> dummy >> dummy;

     while ( str >> x )              
     {
        counter_0 ++ ;
     }
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190