Getting some crazy output... can't figure out the reason.

So I'm working on a program for class, and everything compiles correctly, yet my output is not what it needs to be. The program is supposed to output a list of names and ages, yet it seems that no information is being retrieved from the .txt files. This is the code and output I have at this moment. Can someone take a look and see what I'm doing wrong? Because I sure can't.

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void readFile();
void calculateAge(int[], string[]);

void calculateAge(int year[], string name[])
{
	const int num_years = 10; // Number of years stored.
	const int num_names = 10; // Number of names stored.
	const int currentYear = 2012;
	int age;

	for (int x = 0; x < num_names; x++)
	{
		age = (currentYear - year[x]);
		cout << name[x] << " is " << age << " years old." << endl;
	}
}

void readFile()
{
	const int num_years = 10; // Number of years stored.
	const int num_names = 10; // Number of names stored.
	string name[num_names]; // Array to store names.
	int year[num_years]; // Array to store years.
        ifstream nameFile; // The txt file used to store the names.
	ifstream yearFile; // The txt file used to store the years.
	int x = 0; // Loop 1 counter.
	int y = 0; // Loop 2 counter.

	// Read the years from the txt file.
	yearFile.open("Years.txt");

	while (x < num_years && yearFile >> year[x])
		x++;

	yearFile.close();

	// Read the names from the txt file.
	nameFile.open("Names.txt");

	while (y < num_names && nameFile >> name[y])
		y++;

	nameFile.close();

	calculateAge(year, name);

}

int _tmain(int argc, _TCHAR* argv[])
{
	readFile();

	return 0;
}




 is 858995472 years old.
 is 858995472 years old.
 is 858995472 years old.
 is 858995472 years old.
 is 858995472 years old.
 is 858995472 years old.
 is 858995472 years old.
 is 858995472 years old.
 is 858995472 years old.
 is 858995472 years old.
A lot of tutorials on file stream show the check to make sure the file was opened properly, yet yours doesn't check if that's true. I believe your text file is not being opened and you're not getting any information since, to the program, it doesn't exist.
Thanks for the help, As we both thought, the file wasn't being opened. I just needed to include the full file path instead of just the short "Years.txt"
Last edited on
Topic archived. No new replies allowed.