E
Evyn
HI all,
I have a text file of integers. I can format the file so that the
integers are 1 per line, or continuous.
Reading the file is not a problem. What I want to do is sum the
integers and get a mean. Easy enough, but how do I convert the
character or string I read into type int? I have tried with getline, 1
integer per line in my input file, and get with the integers in 1
line. No luck.
First attempt
-------------------
string line;
ifstream myfile (f);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
// sum = sum + (int) line; // Does not work
running++;
}
myfile.close();
}
else cout << "Unable to open file";
mean = sum/running;
cout << "Mean = " << mean << " sum " << sum << " Running " << running
<< endl << endl;;
second attempt
----------------------
ifstream f1(f);
if(!f1)
{
cout << "Error opening file" << endl;
exit(1);
}
while(f1.get(ch) != NULL)
{
// int tmp = (int) ch; // Not working
sum = sum + tmp;
cout << "ch " << ch << " sum " << sum << endl;
running++;
}
mean = sum/running;
cout << "Mean = " << mean << " sum " << sum << " Running " <<
running << endl;
Any advice/pointers much appreciated.
Regards,
Jim
I have a text file of integers. I can format the file so that the
integers are 1 per line, or continuous.
Reading the file is not a problem. What I want to do is sum the
integers and get a mean. Easy enough, but how do I convert the
character or string I read into type int? I have tried with getline, 1
integer per line in my input file, and get with the integers in 1
line. No luck.
First attempt
-------------------
string line;
ifstream myfile (f);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
// sum = sum + (int) line; // Does not work
running++;
}
myfile.close();
}
else cout << "Unable to open file";
mean = sum/running;
cout << "Mean = " << mean << " sum " << sum << " Running " << running
<< endl << endl;;
second attempt
----------------------
ifstream f1(f);
if(!f1)
{
cout << "Error opening file" << endl;
exit(1);
}
while(f1.get(ch) != NULL)
{
// int tmp = (int) ch; // Not working
sum = sum + tmp;
cout << "ch " << ch << " sum " << sum << endl;
running++;
}
mean = sum/running;
cout << "Mean = " << mean << " sum " << sum << " Running " <<
running << endl;
Any advice/pointers much appreciated.
Regards,
Jim