【问题标题】:c++ reading a file into a struct and writing a binary filec ++将文件读入结构并写入二进制文件
【发布时间】:2016-03-25 17:19:35
【问题描述】:

我有一个包含超过 5000 行数据的文本文件(乐透的抽奖结果)。每行的格式为:数字。日月年 number1,number2,number3,number4,number5,number6

五个示例行:

  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

我也有:

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

我必须将此文本文件中的数据作为 struct Lotto 写入二进制文件。

我的想法已经用完了。 几天以来我一直在尝试,但我的程序仍然无法正常工作:(

我尝试加载一行:)

   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;

【问题讨论】:

  • 向我们展示您的程序
  • "binary file as struct Lotto" Lotto 是一个结构体。谁定义的?你还是你的老师?
  • 我的老师定义的。

标签: c++ text-files fstream binaryfiles objective-c++


【解决方案1】:

以下是一些可能对您有所帮助的观察结果:

  • 您将无法将数字直接读入char。使用中间整数。

  • 定义读取记录的函数:bool read( std::istream&amp;, Lotto&amp; )

  • 你的while应该调用上面的函数:while ( read( is, lotto ) )

起点:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多