How can I count total integer and floating point numbers in a text file?

I have a text file like below read.txt:


1.0 2.0 3.0 4.0
2.0 3.0 4.0 6
5.0 7 1.0 5.0

calc.cpp:

void main()
{
FILE *fp;
fp=fopen("read.txt","r");
double *read_feature = new double*[3];

for(i = 0; i<3; i++)
read_feature[i] = new double[3];

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
fscanf(fp,"%lf",&read_feature[i][j]);
}
}
}

I want to count all the numbers in my text file (read.txt). Read text file consist of floating and integer number. Answer for the above file would be integer=2 and float =10.

When you read the number if it has a decimal point increment a counter.
Read each white space delimited token into a string, and then test if the entire string can be interpreted as an integer.

1
2
3
4
5
6
7
8
9
#include <string>
#include <sstream>

bool is_integer( const std::string& str ) 
{
    std::istringstream stm(str) ; 
    long long test ;
    return stm >> test && stm.eof() ;
}

1
2
3
4
5
6
7
8
int count = 0;
char buff[1024];

while(fgets(buff, 1024, fp))
{
  double Vals;
  count += (sscanf(buff, "%f ", &Vals) + sscanf(buff, "%f\n", &Vals));
}



1
2
3
4
5
int count = 0;
double Vals;

while(fscanf(fp, "%f ", &Vals) || fscanf(fp, "%f\n", &Vals))
  count++;
Topic archived. No new replies allowed.