i want tO add the salaries from a fiLe tO the prOgramme aLL the cOde is compiLing but the problem is that output file is not showing total of the salaries..
the ifstream fiLe cOntents are :
ALi 5000
zeshan 7000
biL 4000
mLik 5000
the ofstream fiLe cOntent should b :
totaL salary =21000
bt it is shOwing
total salary=0
here is the cOde of programme :
#include<iostream>
#include<fstream.h>
#include<cstring>
#include<cstdlib>
using namespace std;
main()
{
ifstream infile; //input file
ofstream outfile; //output fiLe
const int maxchar=100;//maximum nO of characters aLLowed
char readline[maxchar];//char readline decLared tO read frOm Line frOm fiLe
char*token;//pOinter tOken points tO char tO take tOken fOr strtok() functOn
int sal,totalsal=0; //tO caLcuLate(add) saLaries frOm a fiLe
infile.open("salin.txt");
outfile.open("salout.txt");
if(!infile)
{
cout<<"error opening fiLe";
}
if(!outfile)
{
cout<<"error opening fiLe";
}
while(!infile.eof())
{
infile.getline(readline,maxchar);//getline fOr input frOm fiLe
token=strtok(readline," "); //1st tOken is name
token=strtok(NULL," "); //2nd tOken is saLary
}
sal=atoi(token);//atOi cOnvrts char tO int
totalsal+=sal;//add salaries
outfile<<"tOtaL saLary = "<<totalsal;//writing the tOtaL salaty in output fiLe
infile.close(); //cLosing fiLes
outfile.close();
system("pause");
}
#include<iostream>
#include<fstream.h>
#include<cstring>
#include<cstdlib>
usingnamespace std;
main()
{
ifstream infile; //input file
ofstream outfile; //output fiLe
constint maxchar=100;//maximum nO of characters aLLowed
char readline[maxchar];//char readline decLared tO read frOm Line frOm fiLe
char*token;//pOinter tOken points tO char tO take tOken fOr strtok() functOn
int sal,totalsal=0; //tO caLcuLate(add) saLaries frOm a fiLe
infile.open("salin.txt");
outfile.open("salout.txt");
if(!infile)
{
cout<<"error opening fiLe";
}
if(!outfile)
{
cout<<"error opening fiLe";
}
while(!infile.eof())
{
infile.getline(readline,maxchar);//getline fOr input frOm fiLe
token=strtok(readline," "); //1st tOken is name
token=strtok(NULL," "); //2nd tOken is saLary
}
sal=atoi(token);//atOi cOnvrts char tO int
totalsal+=sal;//add salaries
outfile<<"tOtaL saLary = "<<totalsal;//writing the tOtaL salaty in output fiLe
infile.close(); //cLosing fiLes
outfile.close();
system("pause");
}
Lines 32-33 should be inside the while loop. If they're outside the loop, totalSal will be equal to the last salary read from the file.
You shouldn't be looping on eof(). while (infile.getline(readline, maxchar)) would be a better loop condition.
Another possible point of failure: Names generally consist of more than one 'token'. If your salin.txt has first and last names then salaries, you're not parsing the file correctly.