简体   繁体   English

C ++排序二进制文件

[英]C++ Sorting Binary Files

I have a piece of code that won't compile. 我有一段不会编译的代码。

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

I'm getting a compile error that says: fatal error LNK1120: 1 unresolved externals , and I can't figure out why. 我收到一个编译错误,它指出: fatal error LNK1120: 1 unresolved externals ,我不知道为什么。 Also another question is how do you format it so that the data read from the original binary file does not get tampered and is then outputted and saved in a new edited binary file? 还有另一个问题是如何格式化它,以防止从原始二进制文件读取的数据被篡改,然后输出并保存在新的经过编辑的二进制文件中?

You forward declare average like so: 您转发声明average如下所示:

int average (int n);

but you implement average this way: 但是您可以通过以下方式实现平均值:

int average (int n, int size);

If you update your forward declaration and you add the second argument here: 如果更新前向声明并在此处添加第二个参数:

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

that should fix it. 那应该解决它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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