C++ Note 11

advertisement
Library vector
C++ has many dynamic containers, vector is one of them. Those containers make C++ more flexible.
With vector library, we can use vector as an array without knowing the array size.
#include <Iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));//random seed
cout<<”Input an integer number:”;
int num;
cin>>num;
cout<<”Generate “<<num<<” numbers”<<endl;
//generate num random integers
vector<int> container;
for(int I = 0; I < num; i++)
{
int temp = rand()%100;//generate a random number from 0 to 99
container.push_back(temp);//save this random number into the container
}
//print out the container
for(int I = 0; I < container.size(); i++)//call size() to get the number of the elements in the
container
{
Cout<<container[i]<<” “;
}
cout<<endl;
return 0;
}
File input and output
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
//read the records from the input and output to a different file
int main(int argc, char *argv[])
{
vector<string> names;
vector<double> grades;
//read in the records
ifstream inputFile;//create input file stream varialbe
inputFile.open(“./record.txt”);// ./ means the current directory, record.txt is in same folder as
your program
while(!inputFile.eof())
{
string str;
double temp;
inputFile>>str>>temp;//read in one name and one grade
names.push_back(str);
grades.push_back(temp);
}
inputFile.close();//close file stream
//output the records on the screen
for(int I = 0; I < names.size(); i++)
cout<<names[i]<<” “<<grades[i]<<endl;
//output the records into another file
oftream outputFile;
outputFile.open(“./copy.txt”);
for(int i = 0; i < names.size(); i++)
outputFile<<setw(10)<<names[i]<<setw(10)<<grades[i]<<endl;
outputFile.close();
return 0;
}
Record.txt
Martin 99.5
Tom 85.5
……
HW14: read in a book to your program, reverse the order of all words.
Suppose you have book:
This is a long story
Your output should be
story long a is This
Download