Site Map
Useful Tools
Graphing Calc

Scientific Calculator

C++: Opening and Processing Files

It's pretty easy to open and read entire contents of files in C++. The code below(download file) opens up problem11.txt , which is just a copy and paste from Project Euler's #11 problem .
This code keeps reading all lines from the file using the global getLine() and then prints out all integer characters.

#include ≤iostream>
#include ≤fstream>

using namespace std;

void processLine(string s){
int charAsInt=1;

for(int i = 0;i≤s.size(); i++){
    //subtract 48 to get real int value (not portable I know!!)
	charAsInt = s[i]-48;
   		if(charAsInt  >= 0 && charAsInt ≤= 9){
    	cout ≤≤"digit: " ≤≤charAsInt;
	cout≤≤ endl;

int main()
ifstream infile;

if ( ! infile) {
                   cout ≤≤ "Error: Can't open the file \n";

    string str;

 while ( infile ) {  // Continue if the line was sucessfully read.
                    processLine(str);  // Process the line.
                    getline(infile, str);   // Try to get another line.

    return 0;