Hej NG,
Jeg har en irriterende problem med eof test på en ifstream, som
resulterer i, at der læses et ekstra ikke eksisterende blanktegn.
CalculateSum.h
#ifndef CALCULATESUM_H
#define CALCULATESUM_H
#include <iostream>
#include <fstream>
class CalculateSum {
public:
CalculateSum(std::string);
const int getsum(void) const { return sum; }
private:
void compute();
bool string2int(const std::string &, int &);
int sum;
std::ifstream infile;
};
#endif
CalculateSum.cc
#include "CalculateSum.h"
#include "CalculateSumException.h"
#include <sstream>
using namespace std;
bool CalculateSum::string2int(const string &s, int &i)
{
istringstream myStream(s);
if (myStream>>i)
return true;
else
return false;
}
CalculateSum::CalculateSum(string filename)
{
sum = 0;
infile.open(filename.c_str(), ios::in);
if (!infile.is_open())
throw FileNotFoundException(filename);
compute();
}
void CalculateSum::compute(void)
{
string s;
int i;
while (!infile.eof())
{
infile >> s;
if (s != " ")
{
if (!string2int(s, i))
throw BadNumberFormatException(s);
sum += i;
}
}
infile.close();
};
main.cc
#include <unistd.h>
#include <iostream>
#include "CalculateSum.h"
using namespace std;
int main()
{
int sum;
CalculateSum c1("test1.txt");
sum = c1.getsum();
CalculateSum c2("test2.txt");
sum += c2.getsum();
CalculateSum c3("test3.txt");
sum += c3.getsum();
cout << "Sum: " << sum << endl;
return EXIT_SUCCESS;
}
test1.txt
1
2
3
test2.txt
4
5
6
test3.txt
7
8
9
Nogen der har et bud på, hvad der går galt?
--
Hilsen/Regards
Michael Rasmussen
http://keyserver.veridis.com:11371/pks/lookup?op=get&search=0xE3E80917