Sign in
Log inSign up
HOW TO PREPARE FOR A COMPETITIVE PROGRAMMING CONTEST

HOW TO PREPARE FOR A COMPETITIVE PROGRAMMING CONTEST

shuaibu muhammad's photo
shuaibu muhammad
·Sep 18, 2019

I started learning C++ from scratch during my 200 level at Ibrahim Badamasi Babangida University. I knew little about programming, algorithms and data structures at that time. One year and some months after I had written my first line of code, the NUCPC came knocking at the door and it was the perfect time to see if what I have learned was worth anything. After the competition, My team came 8th in the ranking.

I was shocked because I had surpassed competitors with 3 or more years of experience. I knew my team achievement was low, but it exceeded my expectations. The programming contest matched me perfectly and I went all-in in that field.

I know what brought me that achievement and I want to share some with you.

Today, I will show you how to read from a file in c++.

Reading a text file is very easy using an ifstream (input file stream). Include the necessary headers.

#Include <iostream>
#Include <fstream>
using namespace std;

Declare an input file stream (ifstream) variable. For example,

ifstream inFile

Make sure you put the input file in the same project to avoid using path

inFile.open("input.io");

Check that the file was opened. For example, the open fails if the file doesn't exist, or if it can't be read because another program is writing it. A failure can be detected with code like that below using the !(logical not) operator:

if(!infile) {cerr << "Unable to open file input.io"; 
   exit(1);//call system to stop
}

Read from the stream in the same way as cin. For example,

while (inFile > x){
    sum = sum + x;
}

Close the input stream. Closing is essential for output streams to be sure all information has been written to the disk but is also good practice for input streams to release system resources and make the file available for other programs that might need to write it.

inFile.close();

Example The following program reads integers from a file and prints their sum.

//The input file with testcase
1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 

// The code file
#include <iostream>
#include <fstream>
using namespace std;
int main() {
    int sum = 0;
    int x;
    ifstream inFile;

    inFile.open("test.txt");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }

    while (inFile >> x) {
        sum = sum + x;
    }

    inFile.close();
    cout << "Sum = " << sum << endl; 
    return 0;
}