I/O in C++

Out of three programming languages that I’ve learnt, C++ has the simplest way to handle the I/O (input/output). I’m trying to demostrate how to write a program that reads doubles from a file, performs addition of those numbers, and print the results to stdout (standard output).

C++ has useful ifstream and fstream classes that provide a stream interface to read and write data from/to files. The difference between both classes is, ifstream can only be used for reading, while fstream can be used for both reading and writing. Since we’re only going to read the files, we better use ifstream class.

Before we start, make sure you have the test.txt (you can copy mine, if you want). Now, let’s get into the codes (the fun part!):

string inputFile = "test.txt";
ifstream fileIn;
fileIn.open(inputFile.c_str());
if (fileIn.fail())
{
	cerr << "Cannot open file" << endl;
}

Nothing fancy and tricky about the above codes. But notice that, in line 3, I use inputFile.c_str() instead of inputFile to open the file. If you see the C++ Reference, the function open takes the argument const char * for the filename. Since string is an object, we have to convert it to char * which interprets each characters in an array of size N and is used in C language. The function c_str() takes care of the conversion. The code fileIn.fail() checks if failure has occured, i.e. whether the file exists or not. If it fails, return an error.

vector inputs;
double temp;
double adds = 0;
while (!fileIn.eof())
{
	fileIn >> temp;
	if (fileIn.fail())
		break;
	inputs.push_back(temp);
	adds = adds + temp;
}
fileIn.close();

cout << "total: " << adds << endl;
cout << "results:" << endl;

for (int i = 0; i < (int)inputs.size(); i++)
	cout << inputs[i] << endl;

The vector inputs record all the doubles from the specified files. Why do I use vector? Vector makes our life much easier. Unlike the arrays, we don't have to worry about how big the size will be and don't have to bother about resizing it if the size is too small. We just have to declare the vector and use push_back() function to insert the inputs.

In line 6, the stream fileIn extracts the data and stores it in temp which has the parameter type of double. The stream will handle the conversion itself. If the current data in fileIn is not double, it will break out of the loop; as illustrated in code line 7 - 8. The while loop between line 4 and 11 will continue to do its job until the the file points to the eof or end of file. The codes between line 14 and 18 do the usual stuff, i.e. displaying the results to stdout.

You can download the complete .cpp file here (right click & save-as).

6 comments

  1. yup buat data yang dinamis pake vektor lebih bagus buat manajemen memori (halah)
    vector array juga kan mel? tetapi dia rescaleable?

    anyway good work, keep on moving ^^

  2. bintangjatuh : vector itu array dinamis.. berubah” sesuai jumlah datanya.

    belutz : buset. coba kalo udah mengenal berbagai programming language terutama java! omg. it’s not an art nemore, it’s a living hell! –”

    mel : do you agree wif me? LOL

  3. leo: sorry, Leo. I don’t think I agree with you on that one hahaha. So far I find that programming is soooo fun :P. I don’t know what makes me “loves” programming that much. But it really is fun :D.

Leave a Reply to bintangjatuh Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.