2013-02-14 258 views
0

我正在为我的编程类工作:按课程中讨论的实现平均等级程序。成绩信息将显示在一个输入文件中,每个学生的信息分为两行:第一行是名字中间名姓氏格式的学生姓名,第二行是学生的成绩,即整数。 (学生可能没有中间名。)最多有20名学生,每个学生将有10个成绩。程序应该向用户请求输入文件的名称。对于每个学生,计算他们的整体平均值(假设每个任务值得相同的点数)。将信息输出到屏幕上,每个学生一行,每行是他们的'姓名'(姓氏,名字中间初始,10个等级和平均值,按姓氏排序。平均值应该用两位小数显示(即3.1会为3.10输出),你应该使用三个数组这个问题,讨论并通过一套合理的功能。这是我到目前为止所。使用swap按字母顺序排列字符串数组

#include <iostream> 
#include <string> 
#include <fstream> 
#include <climits> 
#include <iomanip> 

using namespace std; 

const int NGrades= 10; 
const int maxStudents=20; 

string reformat(string& s); 

int main(){ 

int num_of_students = 0; 
string fullName; 
double sum=0; 

string names[maxStudents]; 
int grades[maxStudents][NGrades]; 
double average[maxStudents]; 

string fileName; 
ifstream inputFile; 

cout<< "Please type the file name including extension(such as .txt)."<<endl; 
cout<< "If your file is in a different directory please specify the path:"; //asking   user for file name. seperated into two cout statments for readibility 
getline(cin,fileName); 
inputFile.open(fileName.c_str()); 

if (!inputFile){         //produce an error if the file name is invalid 
cout<<"Cannot open "<<fileName<<"."<<endl; 
return 1; 
} 

while(getline(inputFile, fullName)){ 
    names[num_of_students]=reformat(fullName); 
    cout << setw(20)<< names[num_of_students]<<" "<< setw(20); 
    for (int i = 0; i < NGrades; ++i){ 
     inputFile >> grades[num_of_students][i]; 
     cout <<setw(4)<<grades[num_of_students][i]; 
     sum = sum + grades[num_of_students][i]; 
    } 
    average[num_of_students]= sum/NGrades; 
    sum=0; 
    cout <<setw(15); 
    cout<< fixed << showpoint; 
    cout << setprecision(2); 
    cout <<average[num_of_students]<< endl; 
    inputFile.ignore(INT_MAX, '\n'); 
    ++num_of_students; 
} 

inputFile.close(); 

return 0; 
} 
string reformat(string& s){ 
    int pos, posTwo; 
    string first_Middle; 
    string lastname; 
    string finished; 
    pos = s.find_first_of(' '); 
    first_Middle=s.substr(0,pos+2); 
    posTwo=s.find_first_of(' ', pos+1); 
    lastname=s.substr(posTwo+1); 
    finished=lastname+ ", "+first_Middle; 
    return finished; 
} 

我需要做什么现在是按字母顺序排列姓氏使用交换。我不允许使用结构或类似的东西。

+0

使用swap实际上是部分任务吗?你确定你不是指std :: sort吗? – Cogwheel 2013-02-14 03:50:28

回答

0

请先阅读: http://en.wikipedia.org/wiki/Selection_sort

您应该将所有数据存储在三个数组容器中;然后,使用排序算法,您的程序应该正确地打印输出。

询问更具体的问题,比如如何比较字符串。如果有人重写你的代码,你将不会获得知识。