Unexpected output while writing into a text file

Hello, this program produces an output I dont need, and im not sure how to get rid of it, and im guessing its because of 'd'. 'a' takes 'd' place as any number it seems, and because of that, one more calculation happens in display. 0(b) / (random number(a)). How can I fix it ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int d,a,i=1;
double tmp,v=0;
string line;
ifstream file("Text.txt");
if(file.is_open())
{
    file >> d;
    ofstream file2("Result.txt");
    while(getline(file,line))
    {
        istringstream ss(line);
        ss>>a;
        double b=0;
        while(ss>>tmp)
        {
            b+=tmp;
        }
        cout << b << " / " << a << " = " << b/a << ";" << endl;
        file2 << "House nr." << i++ << " min:" << b/a << endl;
        v+=b/a;
    }
    v/=d;
    file2 << "V=: " << v << endl;
    cout << v << endl;
}
return 0;
}
A 'guess' as to what's going wrong isn't nearly as helpful as, say, minimal input file content along with expected and actual output for that input.

You don't check to see if line 19 was successful. Maybe start there.
Expected:

House nr.1 min: 51.733
House nr.2 min: 55.6
House nr.3 min: 39.6
House nr.4 min: 50.725
V= 49.41

What I got:

House nr.1 min: 0
House nr.2 min: 51.733
House nr.3 min: 39.6
House nr.4 min: 50.725
House nr.5 min:50.725
V= 49.41
You didn't supply the input that leads to that, but again I would say:

You don't check to see if line 19 was successful. Maybe start there.


Like this ? if (!(ss>>a) { break;}

If so, then im just getting a 0.
Last edited on
I would guess, then, that there's some difference in the input format you're getting versus what you're expecting, but you didn't supply any input so... hard to say.
4(d)
3(b) (24.5 59.0 71.7(a))
2(b) (45 66.2(a))
2 34.1 45.1
4 45.2 56.4 45.1 56.2
Please don't supply "decorated" input. Just the plain stuff as it appears in the file.

Make your while condition: while (getline(file >> std::ws, line))
You're mixing formatted and unformatted input extraction, and the first time the while loop is entered you have a newline from the previous input operation hanging around in the stream.

Coincidentally, changing that will make getline fail on an empty line which is what it was encountering previously at the end of the file, so testing the ss>>a expression isn't so critical if you can expect the format of the file to be correct otherwise.
Topic archived. No new replies allowed.