8.1 / 8.2
std::istream& test081(std::istream& s)
{
std::string str;
// 从流中读取数据,直至文件结束标识
while (s >> str)
{
// 打印标准输出
std::cout << str;
}
// 对流复位
s.clear();
return s;
}
int main()
{
// 测试函数,调用参数cin
func(std::cin);
}
8.3
当i为文件结束标识,或读取出错,如定义了string,却读入int等
8.4
// 8.4
void test084(const string& file, vector<string> v_str)
{
ifstream in(file);
string str;
if (in)
{
while (getline(in, str))
{
v_str.emplace_back(str);
}
}
}
在编译器中需要inlucde<fstream>
,让编译器看到完整的类定义
8.5
// 8.5
void test085(const string& file, vector<string> v_str)
{
ifstream in(file);
string str;
if (in)
{
while (in >> str)
{
v_str.emplace_back(str);
}
}
}
8.6
int main(int argv, char** argc)
{
ifstream in(argc[0]);
if (!in) return;
Sales_data total;
if (read(in, total))
{
Sales_data trans;
while (read(in, trans))
{
if (total.isbn() == trans.isbn())
{
total.combine(trans);
}
else
{
print(cout, total) << endl;
total = trans;
}
}
print(cout, total) << endl;
}
else
{
cerr << "No data?!" << endl;
}
}
8.7
int main(int argv, char** argc)
{
ifstream in(argc[0]);
if (!in) return;
Sales_data total;
ofstream out(argc[1]);
if (read(in, total))
{
Sales_data trans;
while (read(in, trans))
{
if (total.isbn() == trans.isbn())
{
total.combine(trans);
}
else
{
print(out, total) << endl;
total = trans;
}
}
print(out, total) << endl;
}
else
{
cerr << "No data?!" << endl;
}
}
8.8
将8.7的ofstream out(argc[1]);
改为ofstream out(argc[1], ofstream::app);
8.9
int main(int argv, char** argc)
{
string test_str = "hello world";
istringstream iss(test_str);
test081(iss);
}
8.10
void test0810(string file_name)
{
ifstream in(file_name);
string str;
vector<string> vec;
if (in)
{
while (getline(in, str))
{
vec.emplace_back(str);
}
}
for (string s : vec)
{
istringstream iss(s);
while (iss >> str)
{
cout << str << endl;
}
}
}
8.11
需补充:
istringstream iss;//外部直接定义一个istringstream对象
iss.clear();//循环内部复位
iss.str(line);//循环内部将line拷贝到imm中,返回void
8.12
聚合类不需要初始化
8.13
将getline(cin, line)
改写为
ifstream in(file_name);
string str;
getline(in,str);
8.14
const
: 不修改变量
使用引用: 减少拷贝,提高空间和时间利用
网友评论