Problems with ifstream

I need to create an assignment in which calculates the total price of a list of items and their quantities, however I'm having trouble extracting the numbers from the "bill.in" I'm suppose to refer to.

bill.in contents:
12.75 23
9.5 12
16.25 8

Code that works, but extracts in string
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
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
   ifstream bill;
   bill.open("bill.in");
   
   if(bill.fail())
   {
       cerr<<"Error opening file"<<endl;
       exit(1);
   }

   string a,b,c,d,e,f;
   bill>>a>>b;
   bill>>c>>d;
   bill>>e>>f;

   cout<<"a: "<<a<<endl<<"b: "<<b<<endl<<"c: "<<c<<endl<<"d: "<<d<<endl<<"e: "<<e<<endl<<"f: "<<f<<endl;
}

/*
Output:
a: 12.75
b: 23
c: 9.5
d: 12
e: 16.25
f: 8
(correct output)
*/



Code that does not work, but I wish it would
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
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
   ifstream bill;
   bill.open("bill.in");
   
   if(bill.fail())
   {
       cerr<<"Error opening file"<<endl;
       exit(1);
   }

   int a,b,c,d,e,f;
   bill>>a>>b;
   bill>>c>>d;
   bill>>e>>f;

   cout<<"a: "<<a<<endl<<"b: "<<b<<endl<<"c: "<<c<<endl<<"d: "<<d<<endl<<"e: "<<e<<endl<<"f: "<<f<<endl;
}

/*
Output:
a: 12.75
b: 0
c: 0
d: 0
e: 0
f: 0
*/
Last edited on
I'm not sure if this is your problem but why are you declaring a, c, and e as ints? They are floats are they not?
Topic archived. No new replies allowed.