【问题标题】:How do I use string manipulation to grab certain parts of an input text file?如何使用字符串操作来获取输入文本文件的某些部分?
【发布时间】:2016-07-19 12:32:12
【问题描述】:

我有一个输入文本文件,其中包含 5 行一个人的名字、姓氏和他们的年龄,例如:

Mark Cyprus 21
Elizabeth Monroe 45
Tom McLaugh 82
Laura Fairs 3
Paul Dantas 102

如何使用字符串操作从每一行中获取他们的年龄?

【问题讨论】:

  • 看看我的回答。还记得通过单击答案旁边的空心勾号来accept 一个答案。这也给了您reputation :D 并且也给了回答者应有的信任;-) 您的问题历史表明您从未接受任何答案,这是错误的。您从答案中获取帮助,然后将它们标记为已接受,这就是 Stack Overflow 的工作原理。

标签: c++ string input getline


【解决方案1】:

您可以使用sscanf()(看看链接,它有一个类似于您需要的示例)。

假设每一行文本都读入char数组line

sscanf(line, "%*s %*s %d", &age);

由于您对名字和姓氏不感兴趣,您可以使用%*s,这将允许使用行中的名字和姓氏文字,您不需要将它们分配给任何变量。

下面是完成任务的完整代码,假设您有一个名为“input.txt”的文本文件,其中包含您在问题中给出的文本。

#include <stdio.h>

int main(int argc, char const *argv[])
{
    freopen("input.txt", "r", stdin);
    char line[100];
    int age;
    while(fgets(line, 100, stdin) != NULL)
    {
        sscanf(line, "%*s %*s %d", &age);
        printf("%d\n", age);
    }
    return 0;
}

输出:

21
45
82
3
102

一些链接:

【讨论】:

  • 考虑到问题的兴趣 - 会提到 "%*s %*s %d", &amp;age 禁止分配转换后的字符串,这意味着不需要 first_namelast_name 变量/缓冲区。
  • @TonyD so 即将发布 exact 格式字符串。上升。
  • 我还要添加命名空间std::来标记这个函数来自&lt;cstdio&gt;并且属于c++ std命名空间。
【解决方案2】:

C++中,可以帮助你的工具是std::istringstream,其中包括:#include &lt;sstream&gt;。它的工作原理是这样的:

std::ifstream ifs("mydatafile.txt");

std::string line;

while(std::getline(ifs, line)) // read one line from ifs
{
    std::istringstream iss(line); // access line as a stream

    std::string column1;
    std::string column2;
    std::string column3;

    iss >> column1 >> column2 >> collumn3; // no need to read further

    // do what you will with column3
}

std::istringstream 的作用是让您将std::string 视为输入流,就像普通文件一样。

iss &gt;&gt; column1 &gt;&gt; column2 &gt;&gt; collumn3 将列数据读入变量。

【讨论】:

  • 我认为最好说 if (iss &gt;&gt; column1 &gt;&gt; column2 &gt;&gt; collumn3) ... 来检查该行是否包含三个空格分隔的字符串 - 检查的好习惯。
  • 这很好,谢谢。我总是对这些检查有点懒惰:/
【解决方案3】:

试试这个:

#include<iostream>
#include<string>
#include<fstream>

int main()
{
    std::ifstream fin;
    fin.open("text");
    std::string str;
    while(fin>>str)
    {
        fin>>str;
        fin>>str;
        std::cout<<str<<"\n";
    }
    fin.close();
    return 0;
}

输出:

21
45
82
3
102

【讨论】:

    猜你喜欢
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    相关资源
    最近更新 更多