Regarding reading .txt into struct array

My code is outlined below. I am trying to read in
heart two 2
heart three 3
etc to an array of cards i have named deck. I "think" i may have set up the read correctly, but my file will not open. I always get the "Error" message in the if(!fin.good()) so my text file is not reading correctly. I have no linux password. What can i do to fix this?? I have read your tutorial on i/o files, please help!!

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
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <fstream>
#include stdlib.h>
using namespace std;
const int maxCards = 52;
struct card {
char suit[8];
char rank[6];
//std::string suit; cant use strings
//std::string rank; cant use strings
int cvalue;
char location;
};

//program
int main()
{

//constants
card deck[52];

ifstream myfile;
myfile.open("cardFile.txt");

if(!myfile.good())
{
cout << "ERROR" << endl;
return 0;
}
else
{
for(int i=0; i < maxCards; i++)
{
myfile >> deck[i].suit;
myfile >> deck[i].rank;
myfile >> deck[i].cvalue;    
}
}
for(int i=0; i< maxCards; i++)
{
cout << deck[i].suit << endl;
}

}


When code results in "Error!" printing to terminal. What is wrong with my loop(s)??
Last edited on
There is nothing wrong with your loops (you never reach them).
The fact that you can't open the file, means it is in the wrong place.
It should be in the same directory as your executable.
my file is in the exact same directory as my program.
Are you running the program from the same directory where the executable file is?

try adding
1
2
#include <cerrno>
#include<cstring> 

at the top and then change line 27 to:
cout << "ERROR: " << strerror(errno) << endl

This *might* tell you the problem.
Topic archived. No new replies allowed.