0
編輯。我想感謝在我的代碼中幫助過我的兩個人。截至PST 9/25/2014下午7:22,我修復了我的代碼。儘管如此,排序仍然有問題。在學生班級之間排序名稱
所以我想教自己如何使用C++爲了在學校裏領先我的編程課。我已經採用了Java,所以我對編碼的結構比較熟悉,但不完全確定要輸入什麼內容。這個練習問題是:
1)詢問用戶有多少人想進入列表。
2)閱讀3個字符串,然後將該信息轉換爲學生課,並將學生放入一個向量中。
3)按名稱對列表進行排序。 (額外學分將按學號排序)
4)列出每個學生的信息。
5)詢問用戶,而答案是「是」,在列表中找到的名稱和打印信息相關的名稱
而在Java中,這似乎是很容易的,我有一個非常困難時期瞭解C++中發生了什麼。
我目前只有1,2,4和5完成。這是我迄今爲止所擁有的。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <iomanip>
using namespace std;
class Student
{
string myName, myStudentID, myClassID;
public:
Student(string name, string studentID, string classID)
{
myName = name;
myStudentID = studentID;
myClassID = classID;
}
string getName() { return myName; }
string getStudentID() { return myStudentID; }
void printInfo() { cout << myName << setw(15) << myStudentID << setw(10) << myClassID << endl; }
};
int main()
{
int num;
std::vector<Student> studentList;
cout << "How many students do you wish to add to the student list ? " << endl;
cin >> num;
cin.ignore();
for (int a = 0; a < num; a++)
{
string inputName, inputStudentID, inputClassID;
//get name
cout << "Please enter the Student name : ";
getline(cin, inputName);
//get student ID
cout << "Please enter the Student ID number : ";
getline(cin, inputStudentID);
//get class ID
cout << "Please enter the Student class ID : ";
getline(cin, inputClassID);
Student thisStudent(inputName, inputStudentID, inputClassID);
studentList.push_back(thisStudent);
cout << endl;
}
//sort(studentList.begin(), studentList.end());
/*
I never figured out how to sort the list by name.
I do not know how to compare the name of studentList[0] and studentList[1]
to put them in alphabetical order.
*/
cout << endl;; // FORMATTING
cout << "The student list has a size of " << studentList.size() << endl;
cout << endl;; // FORMATTING
cout << "Student Name" << setw(15) << "Student ID" << setw(10) << "Class ID" << endl;
for (int a = 0; a < studentList.size(); a++)
{
studentList[a].printInfo();
}
cout << endl;; // FORMATTING
string searchedName;
char answer;
do
{
cout << endl;; // FORMATTING
cout << "Please type the name of the person you want to search for: ";
getline(cin, searchedName);
for (int a = 0; a < studentList.size(); a++)
{
if (searchedName.compare(studentList[a].getName()) == 0)
{
studentList[a].printInfo();
break;
}
else
if (a == (studentList.size() - 1)) //If went to end of the list, tell them name not found.
cout << "There is no " << searchedName << " in the list. \n";
}
cout << "Would you like to search for another person? \n";
cout << "Y for Yes, N for No. \n";
cin >> answer;
cin.ignore();
} while (answer == 'Y' || answer == 'y');
return 0;
}
如果你的程序「之類的「你在Visual Studio中,並且你正在尋求領先於你的編程類,那麼現在是學習如何調試的好時機(F5應該在VS2013中開始調試) – Foggzie 2014-09-26 01:05:39
移動'cin。忽視()'如果for循環開始。閱讀[這個答案]的第一部分(http://stackoverflow.com/a/21567292/701092)瞭解發生了什麼 – 0x499602D2 2014-09-26 01:34:34