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.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
void readFile();
void calculateAge(int[], string[]);
void calculateAge(int year[], string name[])
{
constint num_years = 10; // Number of years stored.
constint num_names = 10; // Number of names stored.
constint 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()
{
constint num_years = 10; // Number of years stored.
constint 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"