简体   繁体   中英

c++ reading a file into a struct and writing a binary file

I have a text file that contains over 5000 lines with data (lottery draw results for Lotto). Each line has the form: number. day.month.year number1,number2,number3,number4,number5,number6

Five sample lines:

  1. 27.01.1957 8,12,31,39,43,45
  2. 03.02.1957 5,10,11,22,25,27
  3. 10.02.1957 18,19,20,26,45,49
  4. 17.02.1957 2,11,14,37,40,45
  5. 24.02.1957 8,10,15,35,39,49

I have also:

struct Lotto
{
    short number_drawing;
    char day;
    char month;
    short year;
    char tab[6];
};

I have to write data from this text file into a binary file as struct Lotto.

I have already run out of ideas. I have beeng trying since few days but my program still doesn't work properly :(

I try to load although one line :)

   int main()
{
    ifstream text("lotto.txt", ios::in); 
    ofstream bin("lottoBin.txt", ios::binary | ios::out);
    Lotto zm;
    short number_drawing;
    char day;
    char month;
    short year;
    char tab[6];
    char ch;
    int records = 0;
    while (!text.eof())
    {
        text >> zm.number_drawing >> ch >> zm.day >> ch >> zm.month >> 
ch >> zm.year >> zm.tab[0] >> ch >> zm.tab[1] >> ch >> zm.tab[2] >> 
ch >> zm.tab[3] >> ch >> zm.tab[4] >> ch >> zm.tab[5];
        records++;
    }
    cout << "All records: " << records << endl;

Here are some observations that might help you:

  • You will not be able to directly read a number into a char . Use an intermediate integer.

  • Define a function to read a record: bool read( std::istream&, Lotto& )

  • Your while should call the above function: while ( read( is, lotto ) )

A starting point:

bool read( std::istream& is, Lotto& lotto )
{
  short t;
  char c;

  // read data

  //
  is >> t;
  lotto.number_drawing = t;
  is >> c;
  if ( c != '.' )
    return false;

  //
  is >> t;
  lotto.day = char( t );
  is >> c;
  if ( c != '.' )
    return false;

  // read rest of fields...

  // end of line
  while ( is.get( c ) && isspace( c ) && c != '\n' )
    ;
  if ( ! is.eof() && c != '\n' )
    return false;


  // check data
  if ( lotto.month > 12 )
    return false;

  // check rest of data...

  return is.good();
}


int main()
{
  ifstream is( "yourfile.txt" );
  if ( ! is )
    return -1;

  Lotto lotto;
  while ( read( is, lotto ) )
  {
    // ...
  }
  if ( !is.eof() )
    return -1;


  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM