计算文件C++中每行的整数数量

Count the amount of integers in every line from file C++

本文关键字:整数 数数 文件 C++ 计算      更新时间:2023-10-16

我的任务是计算C++中txt文件中每行的整数数量。

文件格式为:

    Steve Road_43 St43 32 45 2 5 7 23 545
    John Road_21 Dt_4 3 4 5 12 31 0

最后,格式是<字符串字符串int int int int…..int>问题是每行中的整数数量不同,那么我如何知道每行中整数的数量呢?

我的代码->

#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总是零。。不计算整数

一旦str >> x在输入中看到非int类型,str的状态就会设置为fail,并且永远不会恢复。

因此,不会读取任何数字,因为行以非数值开头。

您可以预先消耗两个非int值,然后读取所有int值:

     int x ;
     std::string dummy;
     str >> dummy >> dummy;
     while ( str >> x )              
     {
        counter_0 ++ ;
     }