C++ Input File line by line

Hi there, I need to read some data from a file with string and number that is similar to this:

           
   word1 0.0 1.0 0.0
   word3 word4 0.0 0.0 -1.0
   word1 0.0 0.0 1.0
   word5

With this code:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
    {
      double d1, d2, d3;
      string str1, str2;
      int count=0;
      ifstream infile("file.dat");
      while(infile>> str1 >> d1 >> d2 >> d3 )
          {
          count++;
          cout<<str1<<" " << d1 <<" " <<  d2 <<" " << d3 <<endl;
        }
     cout<<"There are "<<count<<" lines with the string: "<<str1<<endl;
     return 0;
      }

I need to use the linux comand grep to select all the lines with word1 and then I can get the values from file, but I would like to know if I can get the same result within C++ code (i.e. select lines with word1 and then those with word 3 word4)
Thanks in advance!

without knowing what you did with grep it's hard to see what to do with C/C++...

In its simplest form you can do this to print matching lines:

#include <stdlib.h>
#include <string.h>

int main()
{
        char buf[1024];

        while(fgets(buf, 1024, stdin) != NULL)
        {
                if(strstr(buf, "word1") == NULL) continue;
                fputs(buf, stdout);
        }
}
./program < inputfile
1 Like

I used grep to select all the lines with word1:

grep word1 file.dat > filenew.dat

but I am sure that there more elegant way with C++.

See the program above, which matches all lines containing 'word1' and prints them back out.

Thanks Corona688, but with your code how could I assign the values to string str1 and double d1, d2, d3? As in the previous code:

infile>> str1 >> d1 >> d2 >> d3

I'm not sure that code ever worked for one thing. cin, like scanf, has troubles with newlines plugging up the pipeline... using sscanf avoids that.

int main()
{
        char buf[1024];

        while(fgets(buf, 1024, stdin) != NULL)
        {
                char word1[64];
                double d1, d2, d3;
                if(strstr(buf, "word1") == NULL) continue;
                sscanf(buf, "%s %f %f %f", word1, &d1, &d2, &d3);
                printf("got word %s d1 %f d2 %f d3 %f\n", word1, d1, d2, d3);
        }
}