实验测试2《C++ Primer》第五版——第八章 IO类

来源:互联网 发布:c语言源码网站 编辑:程序博客网 时间:2024/06/05 02:39
#include <cstdlib>#include <iostream>#include <fstream>#include <sstream>#include <string>#include <vector>struct PersonInfo {    std::string name;    std::vector<std::string> phones;};int main(int argc, char* argv[]) {    std::string line, word;    std::vector<PersonInfo> people;    std::istringstream record;    if (argc != 3) {        std::cerr << "请给出文件名" << std::endl;        return -1;    }    std::ifstream in(argv[1]);    if (!in) {        std::cerr << "无法打开输入文件" << std::endl;        return -2;    }    while (std::getline(in, line)) {        PersonInfo info;        record.clear();        record.str(line);        record >> info.name;        while (record >> word)            info.phones.push_back(word);        people.push_back(info);    }    in.close();    std::ostringstream os;    os << std::nounitbuf;    for (const auto &entry : people) {        std::ostringstream formatted;        formatted << entry.name;        for (const auto &num : entry.phones) {            formatted << "_" << num;        }        formatted << std::endl;        os << formatted.str();    }    os << std::flush;    std::ofstream out(std::string(argv[2]), std::fstream::app); //C++11    if (!out) {        std::cerr << "无法打开输出文件" << std::endl;        return -3;    }    out << std::unitbuf << os.str();    return 0;}