从文件中读取并在字符串后获取所有字符串

发布于 2025-02-06 15:02:50 字数 391 浏览 3 评论 0原文

我有这样的东西:

while (getline(names_f, line) && getout == true)
{
    istringstream linestream(line);
    linestream >> student_id >> student_name >> student_surname;

只要我有一个函数要考虑名称中的中间名,我就需要在student_id 之后拥有整个行(student_stenter_name>> student_surname

是否可以从student_id的末尾解析此阅读?

I have something like this:

while (getline(names_f, line) && getout == true)
{
    istringstream linestream(line);
    linestream >> student_id >> student_name >> student_surname;

As long as I have a function to consider if there is a middle name in the name, I need to have the whole line after student_id (student_name >> student_surname)

Is it possible to parse this reading from end of student_id?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光是把杀猪刀 2025-02-13 15:02:50

正则表达式使您可以做到这一点,此外,还从语法的角度检查每行是否正确(例如,如果它们以数字开头,是否具有n字段,依此类推)。

[demo]

#include <fmt/core.h>
#include <regex>
#include <sstream>  // istringstream
#include <string>  // getline

int main() {
    std::stringstream iss{
        "1 John Smith\n"
        "2 Sarah Connor\n"
        "3 Peter Gabriel\n"
        "4 Donal Duck\n"
        "5 Wesley Snipes\n"
    };

    for (std::string line{}; std::getline(iss, line); ) {
        std::regex pattern{R"(\d+\s+(\S+\s+\S+\s*))"};
        std::smatch matches{};
        if (std::regex_match(line, matches, pattern)) {
            std::string rest_of_line{ matches[1] };
            fmt::print("'{}'\n", rest_of_line);
        }
    }
}

// Outputs:
//
//   'John Smith'
//   'Sarah Connor'
//   'Peter Gabriel'
//   'Donal Duck'
//   'Wesley Snipes'

Regular expressions let you do that and, besides, check if every line is correct from a syntax point of view (e.g. if they start with a number, if they have n fields, and so on).

[Demo]

#include <fmt/core.h>
#include <regex>
#include <sstream>  // istringstream
#include <string>  // getline

int main() {
    std::stringstream iss{
        "1 John Smith\n"
        "2 Sarah Connor\n"
        "3 Peter Gabriel\n"
        "4 Donal Duck\n"
        "5 Wesley Snipes\n"
    };

    for (std::string line{}; std::getline(iss, line); ) {
        std::regex pattern{R"(\d+\s+(\S+\s+\S+\s*))"};
        std::smatch matches{};
        if (std::regex_match(line, matches, pattern)) {
            std::string rest_of_line{ matches[1] };
            fmt::print("'{}'\n", rest_of_line);
        }
    }
}

// Outputs:
//
//   'John Smith'
//   'Sarah Connor'
//   'Peter Gabriel'
//   'Donal Duck'
//   'Wesley Snipes'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文