C++Primer第五版——习题答案详解(七)



习题答案目录:https://www.cnblogs.com/Mered1th/p/10485695.html

第8章 IO库



练习8.1

istream &iofunc(istream &is) {
    string s;
    while (is >> s) {
        cout << s << endl;
    }
    is.clear();
    return is;
}

练习8.2

#include<iostream>
#include<string>
using namespace std;

istream &iofunc(istream &is) {
    string s;
    while (is >> s) {
        cout << s << endl;
    }
    is.clear();
    return is;
}

int main() {
    iofunc(cin);
    return 0;
}

练习8.3
badbit、failbit和eofbit任一个被置位,则检测流状态的条件会失败。

练习8.4

#include<iostream>
#include<string>
#include<fstream>
#include<vector>
using namespace std;

int fileToVector(string fileName,vector<string> &svec){
    ifstream inFile(fileName);
    if (!inFile) {
        return 1;
    }
    string s;
    while (getline(inFile, s)) {
        svec.push_back(s);
    }
    inFile.close();
    if (inFile.eof()) {
        return 4;
    }
    if (inFile.bad()) {
        return 2;
    }
    if (inFile.fail()) {
        return 3;
    }
}
int main() {
    vector<string> svec;
    string fileName, s;
    cout << "Enter fileName:" << endl;
    cin >> fileName;
    switch (fileToVector(fileName, svec))
    {
    case 1:
        cout << "error: can not open file: " << fileName << endl;
        return -1;
    case 2:
        cout << "error: system failure." << endl;
        return -1;
    case 3:
        cout << "error: read failure." << endl;
        return -1;
    }
    cout << "向量里面的内容:" << endl;
    for (vector<string>::iterator iter = svec.begin();iter != svec.end();++iter)
        cout << *iter << endl;
    return 0;
}

练习8.5

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int fileToVector(string fileName, vector<string>& svec) {
    ifstream inFile(fileName.c_str());
    if (!inFile) {
        return 1;
    }
    string s;

    //习题8.4一次输入一行
    //while (getline(inFile, s)) {
    //  svec.push_back(s);
    //}

    //习题8.5一次一个单词
    while (inFile >> s) {
        svec.push_back(s);
    }
    inFile.close();
    if (inFile.eof()) {
        return 4;
    }
    if (inFile.bad()) {
        return 2;
    }
    if (inFile.fail()) {
        return 3;
    }
}

int main() {
    cout << "测试下" << endl;
    vector<string> svec;
    string fileName, s;
    cout << "Enter filename: ";
    cin >> fileName;
    switch (fileToVector(fileName,svec))
    {
        case 1:
            cout << "error: can not open file: " << fileName << endl;
            return -1;
        case 2:
            cout << "error: system failure." << endl;
            return -1;
        case 3:
            cout << "error: read failure." << endl;
            return -1;
    }

    cout << "向量里面的内容:" << endl;
    for (vector<string>::iterator iter = svec.begin();iter != svec.end();++iter)
        cout << *iter << endl;
    return 0;
}

练习8.6-8.7

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class Sales_data {
public:
    Sales_data() {}
    Sales_data(std::string bN, unsigned sold, double reven) :bookNo(bN), units_sold(sold), revenue(reven) {}
    std::string isbn() const { return this->bookNo; }
    Sales_data& combine(const Sales_data &rhs) {
        units_sold += rhs.units_sold;
        revenue += rhs.revenue;
        return *this;
    }
    double avg_price() const {
        if (units_sold) {
            return revenue / units_sold;
        }
        else return 0;
    }
    Sales_data add(const Sales_data &lhs, const Sales_data &rhs) {
        Sales_data sum = lhs;
        sum.combine(rhs);
        return sum;
    }
public:
    std::string bookNo; //书号
    unsigned units_sold;
    double revenue;
};

istream &read(istream &is, Sales_data &item) {
    double price = 0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = item.units_sold * price;
    return is;
}

ostream &print(ostream &os, const Sales_data &item) {
    os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price()<<"\n";
    return os;
}

int main(int argc, char **argv)
{
    ifstream input(argv[1]);
    ofstream output(argv[2]);

    Sales_data total;

    if (read(input, total))
    {
        Sales_data trans;

        while (read(input, trans))
        {
            if (total.isbn() == trans.isbn())
            {
                total.combine(trans);
            }
            else
            {
                print(output, total);
                cout << endl;
                total = trans;
            }
        }
        print(output, total);
        cout << endl;
        return 0;
    }
    else
    {
        cerr << "No data?!" << std::endl;
        return -1;  // indicate failure
    }
}

练习8.8

ofstream output(argv[2],ofstream::app);

练习8.9

#include<iostream>
#include<string>
#include<fstream>
#include<sstream>
#include<vector>
using namespace std;

istream &iofunc(istream &is) {
    string s;
    while (is >> s) {
        cout << s << endl;
    }
    is.clear();
    return is;
}

int main() {
    string sss;
    cin >> sss;
    istringstream iss(sss);
    iofunc(iss);
    system("pause");
    return 0;
}

练习8.10

#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<sstream>

using namespace std;

int main() {
    string infile = "test.txt";
    vector<string> svec;
    ifstream in(infile);

    if (in) {
        string buf;
        while (getline(in, buf)) {
            svec.push_back(buf);
        }
    }
    else {
        cerr << "can not open the file:" << infile << endl;
    }
    for (auto s : svec) {
        istringstream iss(s);
        string word;
        while (iss >> word) {
            cout << word << endl;
        }
    }

    system("pause");
    return 0;
}

练习8.11

#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<string>

using namespace std;

struct PersonInfo {
    string name;
    vector<string> phones;
};

int main() {
    string line, word;
    vector<PersonInfo> people;
    istringstream record;

    while (getline(cin, line)) {
        record.str(line);
        PersonInfo info;
        record >> info.name;
        while (record >> word) {
            info.phones.push_back(word);
        }
        record.clear();
        people.push_back(info);
    }

    for (const auto &entry : people) {
        cout << entry.name << " ";
        for (const auto &ph : entry.phones) {
            cout << ph << " ";
        }
        cout << endl;
    }

    return 0;
}

练习8.12
vector和string在定义后自动初始化。

练习8.13

#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<string>

using namespace std;

struct PersonInfo {
    string name;
    vector<string> phones;
};

int main() {
    cout << "Please input the fileName:" << endl;
    string infile;
    cin >> infile;
    ifstream in(infile);

    if (!in) {
        cerr << "can not open the file: " << infile << endl;
        return 0;
    }

    string line, word;
    vector<PersonInfo> people;
    istringstream record;

    while (getline(in, line)) {
        record.str(line);
        PersonInfo info;
        record >> info.name;
        while (record >> word) {
            info.phones.push_back(word);
        }
        record.clear();
        people.push_back(info);
    }

    for (const auto &entry : people) {
        cout << entry.name << " ";
        for (const auto &ph : entry.phones) {
            cout << ph << " ";
        }
        cout << endl;
    }
    system("pause");
    return 0;
}

练习8.14
无需修改所以用const,另外引用传值更快。

原文地址:https://www.cnblogs.com/Mered1th/p/10527353.html

时间: 2024-07-31 09:42:22

C++Primer第五版——习题答案详解(七)的相关文章

C++Primer第五版——习题答案详解(五)

习题答案目录:https://www.cnblogs.com/Mered1th/p/10485695.html 第6章 函数 练习6.4 #include<iostream> using namespace std; int fact(int x) { if (x == 1) return x; else return x * fact(x - 1); } int main() { int x; cout << "Please input a number:\n"

C++Primer第五版——习题答案详解

开始刷<C++Primer>这本书,会在博客上更新课后习题. 水平有限,如有有误之处,希望大家不吝指教! 不断学习中,欢迎交流! 第一二章课后题 练习1.3 #include<iostream> int main(){ std::cout<<"Hello world"<<std::endl; return 0; } 练习1.4 #include<iostream> int main(){ std::cout <<

C++Primer第五版——习题答案目录

目前正在刷<C++Primer>这本书,会在博客上记录课后习题答案,答案仅供参考. 因为水平有限,如有有误之处,希望大家不吝指教,谢谢! 目录地址 使用的系统为:win 10,编译器:VS2017,答案用markdown写的. 第1章 开始&&第2章 变量和基本类型 ? 第3章 字符串.向量和数组 ? 第4章 表达式 ? 第5章 语句 ? 第6章 函数 ? 第7章 类 ? 第8章 IO库 ? ? ? ? ? ? ? ? ? ? ? ? ? ? 不断学习中,欢迎交流! 原文地址:

c++ Primer 第五版习题答案第三章

3.2 编写程序,从标准输入中一次读入一整行,然后修改该程序使其一次读入一个词. void readByLine () {    string line; ?    while (getline (cin, line)) {        cout << line << endl;   }   } void readByWord () {    string word; ?    while (cin >> word) {        cout << wo

c++ Primer 第五版习题答案第二章

练习2.1 Q: 类型int.long.long long和short的区别是什么,无符号和带符号类型的区别是什么?float和double的区别是什么? A:int. long. long long和short尺寸不同,表示的数据范围不同.无符号只能表示0和正数,无符号还可以表示负数.float为单精度浮点数,double为双精度,一般来说,float占4字节,double占8字节. 练习2.2 Q: 计算按揭贷款时,对于利率.本金和付款分别应选择何种数据类型?说明你的理由. A: 利率应该用

C++Primer第五版习题解答---第一章

C++Primer第五版习题解答---第一章 ps:答案是个人在学习过程中书写,可能存在错漏之处,仅作参考. 作者:cosefy Date: 2022/1/7 第一章:开始 练习1.3 #include<iostream> int main() { std::cout << "hello, world" << std::endl; return 0; } 练习1.4: #include<iostream> int main() { int

《C++Primer》第五版习题详细答案--目录

作者:cosefy ps: 答案是个人学习过程的记录,仅作参考. <C++Primer>第五版习题答案目录 第一章:引用 第二章:变量和基本类型 第三章:字符串,向量和数组 第四章:表达式 原文地址:https://www.cnblogs.com/cosefy/p/12180771.html

Python核心编程(第二版) 第五章习题答案

5-1.整型.讲讲Python普通整型和长整型的区别. 答:Python 的标准整数类型是最通用的数字类型.在大多数 32 位机器上,标准整数类型的取值范围是-2**31到 2**31-1,也就是-2,147,483,648 到 2,147,483,647.如果在 64 位机器上使用 64 位编译器编译 Python,那么在这个系统上的整数将是 64 位. Python 的长整数类型能表达的数值仅仅与你的机器支持的(虚拟)内存大小有关. 5-2.操作符.(a)写一个函数,计算并返回两个数的乘积.

《C++ Primer 第五版》练习9.51参考答案

//Date.h #include <map> #include <string> #include <vector> using namespace std; struct Date {         explicit Date(const string & info){//检测输入格式,尝试初始化,若失败则进行errorInit             if(mymap.empty()){               initMap();