add each content.read from file

my this programm just doing the square of every first number it gets.
my file is like
120
22
code :
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<fstream>
using namespace std;
int main ()

{
char filename [25];
ifstream myfile;
cin.getline(filename,25);
myfile.open(filename);
if (!myfile.is_open())
{
exit (0);
}
char number[25];
while (myfile.good ())
{
myfile.getline(number,25);

int num=atoi(number);
cout << num + num<< endl;
}
}
output: 240
44
0
i want those two values of file to be added like total= 120 + 22 =142.
240
44
0


From that, I can tell you have a blank line at the end of your file. I don't think you want that.

i want those two values of file to be added like total= 120 + 22 =142.


Well, you need to make another variable, maybe called sum, that will add everything up for you.

Also, why is number a character? That makes no sense. Why not make it an int or a float at the least?

Anyways, a quick example:
1
2
3
4
5
int sum = 0;
//...
sum += num + num;
cout << sum;
//... 
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<fstream>
using namespace std;
int main ()

{
char filename [25];
ifstream myfile;
cin.getline(filename,25);
myfile.open(filename);
if (!myfile.is_open())
{
exit (0);
}
char number[25];
while (myfile.good ())
{
myfile.getline(number,25);

int num=atoi(number);
int sum = 0 ;
sum+= (num + num) ;
cout << sum;
}
}
i did this bt still same result
240
44
0
Put sum at the beginning of main with the rest of your variables. Also, move your cout statement outside of the while loop.
thanks it working now properly
Topic archived. No new replies allowed.