What should I do to change this code using else-if so that it will read the first character in my input text file and then determine which equation to use? For example, the first line in the input text file is A 4 8 and the second line is M 5 9, I want my program to read the first letter and then determine which equation to use. The first line starts with an A so the AddCalculate equation will be used to add 4 and 8 and the second line starts with an M so the MultiplyCalculate equation will be used to multiply 5 and 9. The code that I provided below can only be used to calculate either AddCalculate or MultiplyCalculate. How can I use both AddCalculate and MultiplyCalculate in the same code with else-if to read the first character and determine which equation to use?

#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <iomanip>

#include <fstream>
using std::ifstream;
using std::ofstream;

#include "Calcu.h" 

using namespace std; 


int _tmain(int argc, _TCHAR* argv[])
{
	Calcu myCalcu;

	ifstream inFile ("AorMin.txt");
	ofstream outFile ("AorMout.txt");

	int addthis;
	int addthat;
	int addAnswer;

	int multhis;
	int multhat;
	int mulAnswer;

	if (!inFile)
	{
		cerr << "Error: Input file could not be opened" << endl;
		exit (1);
	}

	if (!outFile)
	{
		cerr << "Error: Input file could not be opened" << endl;
		exit (1);
	}

	while ( !inFile.eof() )
	{	

			inFile >> addthis >> addthat;
			addAnswer = myCalcu.AddCalculate (addthis, addthat);
			outFile << addthis << ", " << addthat << "= " << addAnswer << endl;

			inFile >> multhis >> multhat;
			mulAnswer = myCalcu.MultiplyCalculate (multhis, multhat);
			outFile << multhis << ", " << multhat << "= " << mulAnswer << endl;
			
	}

	cout << "End-of-file reached.." << endl;

	inFile.close();
	outFile.close();

	return 0;
}

You should use the getline function, which reads the first line from input. Then you can use the first character to determine the proper equation to use. Here is an example.

string line;
 //while there is a line to get
while( getline( fileIn, line) ){
 switch( line[0] ){ //check the first letter of the line
   case 'M' : useEquationM(line); break;
   case 'N' : useEquationN(line); break;
   default: throwError("Invalid options!"); break;
 }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.