Help me to read a file but do not read the last line.

There are two files.
The first file(name is filedata1.dat) content is :

1
2
3
4
1            3           8           9
3            6           9           2
2            5           5           8
jfoef


The second file(name is filedata2.dat) content is:
1
2
3
1            3           8           9
3            6           9           2
2            5           5           8


We can see that compared to the second file,the first file have a added last line which is useless for me.

I can read the second file(name is datafile.dat)easily to use the following code(first:g++ xxx.cpp -o xxx.exe then ./xxx.exe):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include<iostream>
  #include<fstream>
  #include<iomanip>
  using namespace std;
  int main()
  {
    ifstream in;
    in.open("datafile2.dat");
    int a[10],b[10],c[10],d[10],i=0; 
    while(true)
    {
      i++;
      in>>a[i]>>b[i]>>c[i]>>d[i];
      if(in.eof()) break;
      cout<<a[i]<<setw(10)<<b[i]<<setw(10)<<c[i]<<setw(10)<<d[i]<<endl;;
    }
    in.close();
  }

however I cant read the first file to use that code!!
who can tell me how to read the first file to get the a[] b[] c[] d[]. Thanks!
Last edited on
This doesn't do what your program does, but should give an idea:
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
#include <vector>
#include <istream>

struct Foo {
  int a;
}

std::istream & operator>> ( std::istream & lhs, Foo & rhs ) {
  int a = 0;
  if ( lhs >> a ) {
    rhs.a = a;
  }
  return lhs;
}

std::vector<Foo> read( std::istream & is ) {
  std::vector<Foo> result;
  result.reserve( 12 );
  Foo foo;
  while ( is >> foo ) // this ends when input fails, be it string or EOF.
  {
    result.push_back( foo );
  }
  return result;
}


However, why does your program use a hardcoded name for the inputfile? Could it read standard input instead? It is trivial to redirect the content of file into standard input of a program.

Furthermore, it is trivial with GNU tools to pipe all but the last line of a file into another program. Thus, your program would never see the offending line.
Last edited on
Hi,keskiverto:
Thanks for your reply.
Can you write a code to help me to read the datafile1.dat to get a[] b[] c[] and d[]?
Thanks again.
Can you write a code

That has no educational benefit.

Why do you want four separate arrays anyway? It is usually more logical and convenient to group related data.
hello keskiverto:

Thank you for your reply.
I have found a method to get what I want.I can use seekg() and tellg() to give a if judgement.
Topic archived. No new replies allowed.