I am transitioning from C to C++ and I am trying to open and read an input file and simultaneously assign variables to the values read in. For example, I have 6 variables: a
, b
, c
, x
, y
,z
and my file: input.dat
looks like this:
1 2 3
4 5 6
So in C I would write:
infile = fopen("input.dat","r");
fscanf(infile, "%d \t %d \t %d \n %d \t %d \t %d \n",&a,&b,&c,&x,&y,&z);
I am trying to do the same thing in C++ using ifstream
but I am having trouble compiling a simple program:
#include <iostream>
#include <fstream>
using namespace std;
main(){
int a, b, c, x, y, z;
ifstream infile("input.dat", ifstream::in); //Open input.dat in input/read mode
if(infile.is_open()){
/*read and assign variables from file - not sure how to do this yet*/
return 0;
} else {
cout << "Unable to open file." << endl;
}
infile.close();
return 0;
}
When I try to compile this I get a ton of errors thrown at me that all look something like:
"Undefined reference to std::cout"
I am sure it is just some silly mistake but I can't seem to figure it out. I was trying to follow the syntax described in the examples at:http://www.cplusplus.com/doc/tutorial/files/
Question:
1.How to properly use fstream
in the above code?
2.How input from files is read and assigned to variables. I understand it can be done with getline
. Is it possible to use the extraction operator >>
and if so, what would the syntax be for this example?