[Solved] How to add two different strings into two variables using getline() in C++?


You can do this by using only getline function, but there is a little bit more elegant solution using both genline and operator >>.

Note: it is work for c++11. It could be rewritten for earlier c++. Look at here for reference.

Only getline using

Here is a program which prints a file with words and its meaning.

#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);
}

Another way

Because operator >> reads one token from a stream, the print_dict function could be rewritten in following way:

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;
  }
}  

1

solved How to add two different strings into two variables using getline() in C++?