vector output to text file
Jun 12, 2012 at 9:51pm UTC
Hi. I'm a computer science student studying c++. My professor gave an assignment where I had to write a program using arrays then convert the program to use vectors. The program had to input information from a text file then alter it and output it to another text file. I finally got it to compile, but the new text file is empty. Help me out please
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 61 62 63 64 65 66 67 68 69 70
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void getInfo(vector<string>, vector<int >);
void outputInfo(vector<string>, vector<int >, vector<int >);
const int CURRENT_YEAR = 2012;
int main()
{
vector<string> names;
vector<int > birthYear;
vector<int > age;
getInfo(names, birthYear);
outputInfo(names, birthYear, age);
return 0;
}
void getInfo(vector<string> firstName, vector<int > year)
{
ifstream inputFile;
int count = 0;
string names;
int years;
inputFile.open("namesandyears.txt" );
while (count < 9)
{
inputFile >> names;
firstName.push_back(names);
inputFile >> years;
year.push_back(years);
count++;
}
inputFile.close();
}
void outputInfo(vector<string> firstName, vector<int > year, vector<int > finalAge)
{
ofstream outputFile;
int count = 0;
int maxNum;
int age;
maxNum = firstName.size();
outputFile.open("birthdayoutput.txt" );
for (count = 0; count < maxNum; count++)
{
age = CURRENT_YEAR - year[count];
finalAge.push_back(age);
}
for (count = 0; count < maxNum; count++)
{
outputFile << firstName[count] << "\t" << year[count] << "\t" ;
outputFile << finalAge[count] << endl;
}
outputFile.close();
}
Jun 12, 2012 at 9:57pm UTC
It is empty because the vectors you are trying to write into the file are also empty.
Last edited on Jun 12, 2012 at 9:57pm UTC
Jun 12, 2012 at 10:06pm UTC
I thought lines 35 - 42 were putting the information from the first file into the vectors. What did I do wrong?
Jun 12, 2012 at 10:12pm UTC
You are filling local variables of the function because its parameters are local veriables. And after exiting the function they are destroyed. You should declare parameters as references to vectors.
Last edited on Jun 12, 2012 at 10:12pm UTC
Jun 12, 2012 at 10:28pm UTC
Thank you!
Topic archived. No new replies allowed.