【问题标题】:Split a line read from a file in C++拆分从 C++ 文件中读取的行
【发布时间】:2020-12-18 20:34:46
【问题描述】:

如何访问从文件中读取的行的各个元素?

我使用以下命令从文件中读取一行:

getline(infile, data) // where infile is an object of ifstream and data is the variable where the line will be stored

以下行存储在 data 中:“The quick brown fox jumped over the lazy dog”

我现在如何访问该行的特定元素?如果我想使用该行的第二个元素 ( quick ) 或获取该行中的某个单词怎么办?如何选择?

任何帮助将不胜感激

【问题讨论】:

  • 您使用的是哪个版本的getline?也就是说,datastring 还是 char[]?你想通过自己在容器中迭代来学习基础知识,还是学习像stringstream这样的高级工具?
  • @Beta 数据是一个字符串。我只是想找到一个简单的解决方案,可以将行的每个元素存储在一个变量中。
  • 您可以将空间上的线(作为字符串)拆分为字符串对象的向量,然后操作向量中的项目。
  • 这能回答你的问题吗? How do I iterate over the words of a string?

标签: c++ file fstream getline


【解决方案1】:

data = "The quick brown fox jumped over the lazy dog",数据是字符串,你的字符串分隔符是" ",你可以用std::string::find()找到字符串分隔符的位置,std::string::substr()得到一个token:

std::string data = "The quick brown fox jumped over the lazy dog";
std::string delimiter = " ";
std::string token = data.substr(0, data.find(delimiter)); // token is "the"

【讨论】:

    【解决方案2】:

    由于您的文本是空格分隔的,您可以使用std::istringstream 分隔单词

    std::vector<std::string> words;
    const std::string data = "The quick brown fox jumped over the lazy dog";
    std::string w;
    std::istringstream text_stream(data);
    while (text_stream >> w)
    {
        words.push_back(w);
        std::cout << w << "\n";
    }
    

    operator&gt;&gt; 会将字符读入字符串,直到找到空格。

    【讨论】:

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