c++ - 分割输入字符串C++

标签 c++

我正在读取一个文件,该文件的每一行都包含这种格式的数据。 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/

相关文章:

c++ - 读取共享内存失败

c++ - 实验室.cpp :112:14: error: no member named 'display' in 'std::vector<Invitee>'

c++ - 模板的自定义迭代器

c++ - 如何告诉编译器使用 C++ 2011 _in_code_ 而不是标志

c++ - 嵌套迭代器访问

c++ - c++函数调用前的空格

c++ - 如何在预编译后通过查看文件来调试Boost?

c++ - 将未知数据类型的元素输入 vector 并传递给函数模板

c++ - 在 C++ 中使用 static_cast 转换指向数组引用的指针是否合法?

c++ - 逆向工程项目到图形 UML 图