我的问题是 C++ 中的 I/O,因为我来自 C,它有点不同。
对于我的程序,每个测试用例都包含一个或多个项目表。项目表包含一行,其中包含大写字母的项目名称,然后是学生的用户 ID,每行一个。我应该打印每个项目的名称,然后是其中的学生人数。我还必须检查已经在项目中的学生并将他们从其他学生中移除。为此,我将 binary_search() 用于学生 ID 的向量中。
一开始我是用cin来换行的。但是,因为 cin 在读取字符串时不考虑空格,所以我转到了 getLine()。但是,当我这样做时,我对“重复”学生 ID 的搜索停止了。我的程序输出也开始打印额外的不需要的 ' ' 在项目名称的末尾。此外,由于某种原因,停止条件“1”和“0”开始保存到我的项目向量中。
这是我的代码:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct project {
string name;
int numStudents;
};
bool operator < (const project& a, const project& b) {
if (a.numStudents != b.numStudents) {
return a.numStudents > b.numStudents;
} else {
return a.name > b.name;
}
}
bool isProjName(string name) {
return name[0] < 97;
}
project criarProjeto(const string& nameProj) {
project proj;
proj.name = nameProj;
proj.numStudents = 0;
return proj;
}
int main () {
string newLine;
do {
vector<string> userIDs;
vector<project> vecProj;
getline(cin, newLine);
while(newLine != "1" && newLine != "0") {
bool isName = isProjName(newLine);
if (isName) {
project newProj = criarProjeto(newLine);
vecProj.push_back(newProj);
}
else if (!binary_search(userIDs.begin(), userIDs.end(), newLine)) { //This stopped working after switching to getLine
userIDs.push_back(newLine);
sort(userIDs.begin(), userIDs.end());
vecProj.back().numStudents++;
}
getline(cin, newLine);
}
sort(vecProj.begin(), vecProj.end());
for (unsigned long j = 0; j < vecProj.size(); j++) {
cout << vecProj[j].name << " " << vecProj[j].numStudents << endl;
}
} while (newLine != "0");
}
期望的输出:
YOUBOOK 2
LIVESPACE BLOGJAM 1
UBQTS TXT 1
SKINUX 0
我的输出:
YOUBOOK
2
LIVESPACE BLOGJAM
2
UBQTS TXT
1
SKINUX
0
1
0
我尝试手动并通过 erase() 删除 ' ' 从 newLine 的末尾开始,但它要么不起作用,要么给我错误。我在打印输出时尝试使用 pop_back(),虽然它确实纠正了输出格式问题,但它没有纠正 binary_search() 函数或将停止条件“1”和“0”存储到我的项目向量中。
非常感谢您的阅读。