第十七章:输入、输出和文件
一、复习题
1. iostream文件构建了控制台与程序之间的I/O。
2. 因为系统只会读入字符,要想读入数字,需要将若干个字符转换为单个数字
3. 默认都输出到显示器,但前者能重定向,后者不能
4. 因为cout类对基本类型进行了<<运算符的重载
5. <<运算符重载的方法返回的是ostream的引用
6. 略
7. 略
8. Iseeaq
I see a q
ct1 = 5 ; ct2 = 9
9. 在字符超过80个且其中没有‘\n'时,第一条语句清空所有的字符,但第二条语句只能清空前80个字符。
二、编程练习
4.
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
ifstream fin1("data1");
ifstream fin2("data2");
ofstream fout("data3");
vector<string> d1;
vector<string> d2;
string str;
while (getline(fin1, str))
{
d1.push_back(str);
str.clear();
}
while (getline(fin2, str))
{
d2.push_back(str);
str.clear();
}
fin1.close();
fin2.close();
int line = min(d1.size(), d2.size());
for (int i = 0; i < line; ++i)
{
fout << d1[i] + " " + d2[i] << "\n";
}
if (d1.size() > d2.size())
{
for (int i = line; i <= d1.size() - d2.size() + line; ++i)
{
fout << d1[i] << "\n";
}
}
else
{
for (int i = line; i <= d2.size() - d1.size() + line; ++i)
{
fout << d2[i] << "\n";
}
}
fout.close();
return 0;
}
7.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
void ShowStr(const std::string &str)
{
std::cout << str << std::endl;
}
class Store
{
private:
std::ofstream& fout;
public:
Store(std::ofstream& o) : fout(o){}
void operator()(const std::string& str)
{
size_t len = str.size();
fout.write((char *)&len,sizeof(size_t));
fout.write(str.data(),len);
}
};
void GetStrs(std::ifstream& in, std::vector<std::string>& data)
{
size_t len;
while(in.read((char*)&len,sizeof (size_t)))
{
std::string str;
char ch;
for(int i = 0; i < len; ++i)
{
in.read(&ch, sizeof(char));
str.push_back(ch);
}
data.push_back(str);
}
}
int main()
{
using namespace std;
vector<string> vostr;
string temp;
cout << "Enter strings (empty line to quit):\n";
while (getline(cin, temp) && temp[0] != '\0')
vostr.push_back(temp);
cout << "Here is your input.\n";
for_each(vostr.begin(), vostr.end(), ShowStr);
ofstream fout("strings.dat", ios::out | ios_base::binary);
for_each(vostr.begin(), vostr.end(), Store(fout));
fout.close();
vector<string> vistr;
ifstream fin("strings.dat", ios::in | ios_base::binary);
if (!fin.is_open())
{
cerr << "Could not open the file.\n";
exit(EXIT_FAILURE);
}
GetStrs(fin, vistr);
cout << "\nHere are the strings read from the file.\n";
for_each(vistr.begin(), vistr.end(), ShowStr);
return 0;
}