Reading and Processing a File Line by Line in C++

In C++, how to process a file line by line? The file is a plain text line like input.txt. As an example, the process can be to just print it out.

In C++, you may open a input stream on the file and use the std::getline() function from the <string> to read content line by line into a std::string and process them.

std::ifstream file("input.txt");
std::string str; 
while (std::getline(file, str)) {
  // process string ...
}

A full example is as follows:

$ g++ file-read-line.cpp -o s && ./s
$ cp file-read-line.cpp input.txt
$ ./s
#include <iostream>
#include <fstream>
#include <string>

int main ()
{
  std::ifstream file("input.txt");
  std::string str;
  while (std::getline(file, str)) {
    std::cout << str << "\n";
  }
}

Similar Posts

  • Transactional memory learning materials

    I want to learn transactional memory technologies. Any suggestions on Transactional memory learning materials? Thanks! I highly suggest the Transactional Memory lecture by James R. Larus and Ravi Rajwar of Synthesis Lectures on Computer Architecture: The Transactional Memory lecture:http://www.morganclaypool.com/doi/abs/10.2200/S00070ED1V01Y200611CAC002 Link to the PDF:http://www.morganclaypool.com/doi/pdf/10.2200/S00070ED1V01Y200611CAC002 Read more: Mmaping Memory Range Larger Than the Total Size of Physical…

  • |

    How to compare date in SQL?

    How to compare date in SQL? For example, the ‘users’ table has a column ‘loggin’ which is the date and time. How to find out the ‘users’ whose ‘loggin’ date is later than Jan 10, 2017? In SQL, dates can be compared using ‘’, ‘=‘. For the example described, the SQL statement could be: SELECT…

  • How to set process with lowest priority?

    In system, sometimes, we need backstage threads with very very low priority since it cannot preempt any normal process asks for CPU. SCHED_IDLE class satisfies this requirement which has the priority lower than “nice=19” of CFS. Following code does this. 241 void set_idle_priority(void) { 242 struct sched_param param; 243 param.sched_priority = 0; 244 int s…

  • Patching with git

    Tutorials on how to create patches and apply patches with git. A nice tutorial: https://ariejan.net/2009/10/26/how-to-create-and-apply-a-patch-with-git/ Manuals: git format-patch: https://www.systutorials.com/docs/linux/man/1-git-format-patch/git apply: https://www.systutorials.com/docs/linux/man/1-git-apply/ Read more: How to create a git branch on remote git server How to do diff like `git diff –word-diff` without git on Linux? Cheatsheet: Git Branching with a Git Server What about the…

4 Comments

  1. but Why you the loop is not accessible after using it i want the loop to be accessible every time not only one time plz

Leave a Reply

Your email address will not be published. Required fields are marked *