如何在C ++中使用getline()将两个不同的字符串添加到两个变量中?

时间:2014-10-12 14:08:26

标签: c++ string file-handling

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

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

我想将“Car”作为单词和“四轮汽车”作为每行的含义等等。可以使用getline()函数完成吗?还有另一种简单的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以仅使用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 >>从流中读取一个标记,所以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;
  }
}