need help, how to use vector?
Sep 18, 2013 at 1:03am UTC
Write a program to read 10 name from and input file, each name has 5 grades (from another input file)
now display and print them to an output file. Send input files, source code, and output file for grading
HERE IS MY ASSIGNMENT, I JUST FINISHED IT BY USING ARRAY, BUT I WAS WONDERING IF ANY BODY COULD TEACH ME HOW TO DO IT BY USING VECTOR? THANKS!
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
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
const int Num=10;
const int iScore=50;
string names[Num];
string score[iScore];
int count;
ifstream inFile;
ifstream inFile1;
ofstream outFile;
inFile.open("D:\\names.txt" );
outFile.open("D:\\nameslin.txt" );
for (count=0; count<Num;count++)
{
inFile>>names[count];
}
inFile.close();
inFile1.open("D:\\grades.txt" );
for (count=0; count<iScore; count++)
{
inFile1>>score[count];
}
inFile1.close();
for (count=0; count<Num;count++)
{
int index=count*5;
outFile<<setw(2)<<right<<count+1<<" : " ;
outFile<<setw(6)<<names[count]
<<" : " <<score[index]
<<" " <<score[index+1]
<<" " <<score[index+2]
<<" " <<score[index+3]
<<" " <<score[index+4]<<"\n" ;
}
outFile.close();
cout<<"These names are:\n" ;
for (count=0; count<Num;count++)
{
cout<<setw(3)<<count+1<<": " ;
int index=count*5;
cout <<setw(6)<<names[count]
<<" : " <<score[index]
<<" " <<score[index+1]
<<" " <<score[index+2]
<<" " <<score[index+3]
<<" " <<score[index+4]<<"\n" ;
}
return 0;
}
Last edited on Sep 18, 2013 at 1:05am UTC
Sep 18, 2013 at 1:42am UTC
these two functions read/write a vector to and from a file. You could use them to implement in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
//write vector to file spaced by index, separated by sep
void write(std::string filename, std::vector<std::string> v, std::string sep="\n" ){
std::ofstream f;
f.open(filename);
for (std::vector<int >::size_type i = 0; i != v.size(); i++) {
f << v[i] << sep;
}
f.close();
}
//open file and read into vector str
std::vector<std::string> open(std::string filename){
std::string s = "" ;
std::vector<std::string> v;
std::ifstream f;
f.open(filename);
while (getline(f, s)){
v.push_back(s);
}
f.close();
return v;
}
Last edited on Sep 18, 2013 at 1:43am UTC
Sep 19, 2013 at 1:18pm UTC
thx a lot!
Topic archived. No new replies allowed.