Read file line by line using ifstream in C++

First, make an ifstream: The two standard methods are: Assume that every line consists of two numbers and read token by token:int a, b; while (infile >> a >> b) { // process pair (a,b) } Line-based parsing, using string streams:#include <sstream> #include <string> std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); int a, b; if … Read more

Read file line by line using ifstream in C++

First, make an ifstream: The two standard methods are: Assume that every line consists of two numbers and read token by token: int a, b; while (infile >> a >> b) { // process pair (a,b) } Line-based parsing, using string streams: #include <sstream> #include <string> std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); int … Read more

Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

Make sure the file exists: use os.listdir() to see the list of files in the current working directory Make sure you’re in the directory you think you’re in with os.getcwd() (if you launch your code from an IDE, you may well be in a different directory) You can then either: Call os.chdir(dir), dir being the … Read more

Print string to text file

It is strongly advised to use a context manager. As an advantage, it is made sure the file is always closed, no matter what: This is the explicit version (but always remember, the context manager version from above should be preferred): If you’re using Python2.6 or higher, it’s preferred to use str.format() For python2.7 and higher … Read more