【问题标题】:C++ Sorting Binary FilesC++ 对二进制文件进行排序
【发布时间】:2013-06-04 01:59:12
【问题描述】:

我有一段无法编译的代码。

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <Windows.h>
#include <iomanip>
using namespace std;


int average (int n);

int main() 
{

string filename;

int i,j;
int n = 0;
int sum = 0;
int size = 4;
const int nameLength = 19;
const int maxRecords = 100;
int index[100];


int scores[maxRecords];
char names[maxRecords][nameLength];

int count = 0;

cout << "Enter binary data directory and file name: ";
getline (cin, filename);
// Open file for binary read-write access.
    ifstream fin(filename.c_str(), ios::binary);

if (!fin) {
cout << "Could not open " << filename << endl;
system("PAUSE");
return -1;
}

// Read data from the file.
while (
fin.read(names[count], sizeof(names[0]))
     && fin.read((char *) &scores[count], sizeof(scores[0]))
)
{

    count++;
    fin.ignore(); // skip the padding byte
}


// Display the data and close.
 cout << "Your file's data unsorted: " << endl;
cout << endl;
    cout << setw(10) << "Name" << setw(20) <<  "Test Score" << endl;

    for (i=0;i<n;i++){
            cout << setw(10) << names[i] << setw(20) << scores[i] << endl;
    }

            for (i=0;i<n;i++)
    {
            index[i]=i;
    }

    for (i=0;i<n;i++)
    {

            for (j=i+1;j<n;j++)
            {
                    int temp;
                    if (scores[index[i]] > scores[index[j]])
                    {
                            temp = index[i];
                            index[i] = index[j];
                            index[j] = temp;
                    }
            }
    }

    cout << "The average of the test scores in your file is:  " << average         (sum);

sum=sum+scores[i];


fin.close();
system("PAUSE");
return 0;
}

int average (int sum, int size)
{ 
return sum/size;
}

我收到一个编译错误,上面写着:fatal error LNK1120: 1 unresolved externals,我不知道为什么。还有一个问题是如何格式化,这样从原始二进制文件中读取的数据不会被篡改,然后输出并保存在一个新的编辑二进制文件中?

【问题讨论】:

  • 确切的错误信息是什么?
  • 为什么包含&lt;windows.h&gt;,但不包含&lt;cstdlib&gt;?我在这里没有看到前者的任何东西,但 system 来自后者,而不是 system("PAUSE") 是代码应该有的东西。
  • 错误消息说,“”致命错误 LNK1120: 1 个未解决的外部问题“”,我之前有 因为我在那里取出了一个 MAX_PATH 的东西。
  • @user2444400,我只询问&lt;windows.h&gt;,因为它非常大。这是一组巨大的标题。

标签: c++ file sorting binary


【解决方案1】:

你像这样转发声明average

int average (int n);

但你以这种方式实现平均:

int average (int n, int size);

如果您更新前向声明并在此处添加第二个参数:

cout << "The average of the test scores in your file is:  " << average(sum,size);

应该可以解决它。

【讨论】:

  • 好的,谢谢修复,但现在这是我的输出:输入二进制数据目录和文件名:C:\Users\Jacky\Desktop\project6.dat 您的文件数据未排序:名称测试分数您文件中的平均考试成绩为: 0按任意键继续。 . .
  • 现在你必须修复你的程序。 :)
  • 是的,但会不会是我的排序搞砸了输出?
  • @user2444400 一些提示:仔细阅读您的输入循环。然后仔细检查输出和排序循环中的界限。看看你是如何计算总和的。
猜你喜欢
  • 2011-11-28
  • 2017-02-02
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2019-04-20
  • 2019-03-12
相关资源
最近更新 更多