【问题标题】:How to add two different strings into two variables using getline() in C++?如何在 C++ 中使用 getline() 将两个不同的字符串添加到两个变量中?
【发布时间】:2014-10-12 14:08:26
【问题描述】:

我想使用 getline() 函数将一个单词和它的含义从文件中添加到两个不同的字符串变量单词和含义中。 文本文件如下:

Car an automobile with four wheels
Bike an automobile with two wheels

我想为每行存储“汽车”作为单词,“一辆有四个轮子的汽车”作为含义,依此类推。可以使用 getline() 函数来完成吗?还有其他简单的方法吗?

【问题讨论】:

    标签: c++ string file-handling


    【解决方案1】:

    您可以只使用getline 函数来做到这一点,但是使用genlineoperator >> 有一个更优雅的解决方案。

    注意:适用于 c++11。它可以为早期的 c++ 重写。参考here

    getline 使用

    这是一个打印带有单词及其含义的文件的程序。

    #include <fstream>
    #include <iostream>
    #include <string>
    
    void print_dict(std::string const& file_path) {
      std::ifstream in(file_path);
      std::string word, meaning;
      while (std::getline(in, word, ' ')) { // reads until space character
        std::getline(in, meaning);          // reads until newline character
        std::cout << word << " " << meaning << std::endl;
      }
    }
    
    int main() {
      std::string file_path = "data.txt";
      print_dict(file_path);
    }
    

    另一种方式

    因为operator &gt;&gt; 从流中读取一个令牌,所以print_dict 函数可以重写为以下方式:

    void print_dict(std::string const& file_path) {
      std::ifstream in(file_path);
      std::string word, meaning;
      while (in >> word) {         // reads one token
        std::getline(in, meaning); // reads until newline character
        std::cout << word << " " << meaning << std::endl;
      }
    }  
    

    【讨论】:

    • 非常感谢,它有效。抱歉,如果我的问题不具体,我是新来的。
    猜你喜欢
    • 2014-04-05
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    相关资源
    最近更新 更多