read from file

closed account (4w7X92yv)
Hello

I need to write a program that uses data from an extra file in the same directory as the main program

this is the program im using at this moment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main()
{
 
 double x1,x2,x3;
 
 cin >> x1 >> x2 >> x3;
 
 cout << "the numbers are: " << x1 << ", " << x2  << " and " << x3 << endl;;
 
 system ("pause");
 return 0;    
}


and what it should do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main()
{
 
 double x1,x2,x3;
 
 //read the x1, x2, x3 from the file
 
 cout << "the numbers are: " << x1 << ", " << x2  << " and " << x3 << endl;;
 
 system ("pause");
 return 0;    
}


How can i make this happen?

Best Regards
Joriek
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
 
 double x1,x2,x3;
 fstream fin( "file.txt" );
 fin >> x1 >> x2 >> x3;
 
 cout << "the numbers are: " << x1 << ", " << x2  << " and " << x3 << endl;;
 
 system ("pause");
 return 0;    
}


This expects the file to be in this format (single line, whitespace separated values):
1.0 2.0 3.0


Note that this does no error handling. Things will only work out if the file has well-formated input data.
Last edited on
closed account (4w7X92yv)
thanks
This should help you even gives some examples

http://www.cplusplus.com/doc/tutorial/files/
Topic archived. No new replies allowed.