structs are frustrating

Pages: 12
1. You're trying to switch on an undefined variable. At no point have you created a "month" in your main.

2. Single quotes denote a character. Characters are only 1 character long (unless they are special and prefaced with \ ). This is where your error is coming from. Since I'm assuming you mean to switch on f.month, just remove the quotes.
Some additional comments:

Line 26: If you can not open the file, you should exit the program after displaying the message, otherwise you're going to continue inline as if the file was opened.

Line 35: Do not loop on !eof(). This does not work the way you expect. eof is set true only after you make a read attempt on the file. This means after you read the last record of the file, eof is still false at line 35. Attempting to read past the last record at line 37 sets eof, but you're not checking it there. You proceed as if you had read a good record. This will result in reading an extra (bad) record. The correct way to deal with this is to put the entire cin operation as the condition in the while statement.
1
2
3
4
while (inFile >> f.fname >> f.lname >> f.month >> f.day >> f.year)
{  // A record was read 
...
}


Last edited on
Thank you for all the help thus far. I am not sure if i can break up the dob into month, day , year with just a switch. How could I break up the dob if it is the format of 01/11/1234?

Here is my code:

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
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <fstream>

using namespace std;

struct friends
{
	string fname;
	string lname;
	string dob;
};

int main(){
	
	ifstream inFile;
	inFile.open("friends.txt");
		
if(!inFile)
{
	cout << "Unable to open file. Please check the file." << endl;
}
friends f;
int index = 1;
int month;
int day;
int year;
while(!inFile.eof())
{
	inFile >> f.fname >> f.lname >> f.dob;
	
	string name = f.fname + ' ' + f.lname;
	cout << index << "." << name << setw(30) << setfill(' ') << f.dob << endl;
	index++;
}

system("Pause");
return 0;
}
I was going to try using cin.ignore but I'm not sure if that would work.
Topic archived. No new replies allowed.
Pages: 12