Vefhug
Vefhug

Reputation: 149

How to save each string in a text file C++

I have a txt file, named mytext.txt, from which I want to read and save every line in C++. When I run the binary, I do ./file <mytext.txt

I'd like to do something

std::string line;
while(std::getline(std::cin,line)){
//here I want to save each line I scan}

but I have no clue on how to do that.

Upvotes: 0

Views: 730

Answers (2)

ruudscheenen
ruudscheenen

Reputation: 44

You can look at the following documentation and example:

http://www.cplusplus.com/doc/tutorial/files/

Edit upon recommendation:

In the provided link below they explain how to open and close a text file, read lines and write lines and several other functionalities. For completeness of this answer an example will be given below:

// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

The above script will write the 2 lines into the text file named example.txt.

You can then read these lines with a somewhat similar script:

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

Best regards

Ruud

Upvotes: 0

Cosmin Petolea
Cosmin Petolea

Reputation: 119

You can use a std::vector<string> to save the lines as so:

///your includes here
#include <vector>

std::vector<std::string> lines;
std::string line;
while(std::getline(std::cin,line))
    lines.push_back(line);

Upvotes: 1

Related Questions