C++ fil-läsning
Hej! Jag har ett problem där man ska läsa in en textfil som ser ut som följande:
10
1
12.345
this is to ignore
101
-10
100000
1859 -1243 -734 XPTO 1455 1818 -774 -89 -475 -1145 1501 1049 -4 1084
Här ska man endast läsa in talen som doubles och alltså ignorera blanksteg och bokstäver. Sen ska man avrunda talen, "10-logaritmera" och skriva ut till en textfil som enligt exempel ska se ut enligt följande:
log(10.000) = 1.000
log(1.000) = 0.000
log(12.345) = 1.091
log(101.000) = 2.004
log(100000.000) = 5.000
log(1859.000) = 3.269
log(1455.000) = 3.163
log(1818.000) = 3.260
log(1501.000) = 3.176
log(1049.000) = 3.021
log(1084.000) = 3.035
So far so good... Men min ut-fil får några småfel och ser ut såhär:
log(10.000) = 1.000
log(1.000) = 0.000
log(12.345) = 1.091
log(1455.000) = 3.163
log(1818.000) = 3.260
log(1501.000) = 3.176
log(1049.000) = 3.021
log(1084.000) = 3.035
Här kommer den kod jag har skrivit:
#include<iostream>
#include<iomanip>
#include<cmath>
#include<string>
#include<sstream>
using namespace std;
/*******************************
* 1. function declarations *
********************************/
string convert_log(double d);
/*******************************
* 2. Main function *
*******************************/
int main()
{
double d;
while(!cin.eof())
{
if(cin >> d && d>0)
{
//cout << "log(" << setprecision(3) << fixed << d << ") = " << convert_log(d);
cout << convert_log(d);
}
else
{
cin.clear();
cin.ignore(256, ' ');
}
}
return 0;
}
/*******************************
* 3. Functions implementation *
********************************/
string convert_log(double d)
{
if(d > 0)
{
ostringstream result;
double temp=0;
d += 0.0005;
d *= 1000;
d = (int)d;
d /= 1000;
temp = log10(d);
result << fixed << setprecision(3) << "log(" << d << ") = " << temp << endl;
//result << temp << endl;
return result.str();
}
else
{
return "";
}
}
Förstår inte vad jag har gjort för fel?
Tack på förhand!