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;


	return 0;

Edited by Narue: Added code tags

6 Years
Discussion Span
Last Post by firstPerson

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;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.