我正在读取一个文件,该文件的每一行都包含这种格式的数据。 30304 Homer Simpson
我需要能够将其传递给以下构造函数,整数是 regNo,名称是字符串的其余部分,每个学生都会有自己的标记图。
Student::Student (string const& name, int regNo):Person(name)
{
regNo = regNo;
map<string, float> marks;
}
然后,我必须将每个学生添加到学生集合中,这将是最好的,我该如何做到这一点?
到目前为止,我所要做的就是获取文件名并检查它是否存在。
int main()
{
//Get file names
string studentsFile, resultsFile, line;
cout << "Enter the Students file: ";
getline(cin, studentsFile);
cout << "Enter the results file: ";
getline(cin, resultsFile);
//Check for students file
ifstream students_stream(studentsFile);
if (!students_stream) {
cout << "Unable to open " << studentsFile << "\n";
return 1;
}
}
我尝试使用带有 3 个参数和“”作为分隔符的 getline,但这也会分割字符串的名称部分,所以我不确定如何以另一种方式执行此操作。
最佳答案
当然,将 std::cin
替换为您的输入文件流。 “修剪”名称结果可能是明智的,除非您 100% 知道输入格式正确。我只添加了最低限度的错误状态处理以某种方式“生存”。
当然,也可以读取单个/三个/更多变体的名称,正如任何现实世界的应用程序应该那样。
#include <iostream>
#include <string>
#include <stdexcept>
int main()
{
std::string line, name;
unsigned long long regNo;
size_t nameOfs;
while (true) {
// Read full non-empty line from input stream
try {
std::getline(std::cin, line);
if (line.empty()) break;
}
catch(const std::ios_base::failure & readLineException) {
break;
}
// parse values:
// 1. unsigned long long ending with single white space as "regNo"
// 2. remaining part of string is "name"
try {
regNo = std::stoull(line, &nameOfs);
name = line.substr(nameOfs + 1);
}
catch(const std::logic_error & regNoException) {
// in case of invalid input format, just stop processing
std::cout << "Invalid regNo or name in line: [" << line << "]";
break;
}
// here values regNo + name are parsed -> insert them into some vector/etc.
std::cout << "RegNo [" << regNo << "] name [" << name << "]\n";
}
}
关于c++ - 分割输入字符串C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41614228/