【发布时间】:2018-03-07 04:55:54
【问题描述】:
我正在学习基础 C++ 大学课程,但我完全被我的一项作业困住了。
我需要从包含 (1-25) 个名称列表的文件中读取输入,按字母顺序对名称进行排序,然后输出哪些人将位于行的前面(例如:Amy)和后面行的(例如:Zora)。我的教授很讲究,他严格禁止我们使用我们在课堂上没有学到的任何东西。我们只学过cin、cout、if语句、循环、基本操作符、fstream和基本字符串。
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
//Intialize variables
string studentName;
string firstEntry;
string secondEntry;
string first;
string last;
ifstream inputFile;
string filename;
int students;
//Ask for amount of students
cout << "Please enter the number of students in the class.\n(The number must be a whole number between 1 and 25.)\n";
cin >> students;
//Input validation
while (students < 1 || students > 25)
{
cout << "\nInvalid value. Please enter a value between 1 and 25.\n";
cin >> students;
}
//Get file name from user
cout << "Please enter the name of the file with the list of students\n";
cin >> filename;
//Open the file
inputFile.open(filename);
if (inputFile)
{
while (inputFile >> studentName)
{
cin >> studentName;
studentName = firstEntry;
cin >> studentName;
studentName = secondEntry;
if (firstEntry < secondEntry)
{
firstEntry = first;
secondEntry = last;
}
}
cout << first << " is the first student in line.";
cout << last << " is the last student in line.";
}
else
{
cout << "Error opening the file.\nPlease restart the program and try again.";
return 1;
}
inputFile.close();
return 0;
}
这也是我正在阅读的文件:
杰基
山姆
汤姆
比尔
玛丽
保罗
泽夫
倒钩
我主要停留在从文件读取和解释数据部分。
【问题讨论】:
-
那么我们应该如何知道您在课堂上学到了什么,即允许或不允许什么?您最好列出到目前为止您上过的每节课,这样我们就不会给您提供您尚未学习的建议。
-
如果不知道您所学的主题,将很难为您提供建议。既然是作业,那就用你的技能解决手头的问题吧。有很多方法可以解决问题..但如果你自己做。那么这将有助于您了解基本的编程结构。
-
如果只需要第一个和最后一个,就不用担心对整个列表进行排序。类似的问题是返回整数列表中的最小值和最大值。
标签: c++ sorting alphabetical