0

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.

0

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

posting only a link as answer is as good as saying "you can google it". Adding links is fine, but then at least summarize

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.