C++ Primer 5th 课后习题8.10、8.11、8.13

//习题8.10
int main()
{
    ifstream in("1");
    if (!in) {
        cerr << "无法打开文件" << endl;
    }
    string line;
    vector<string> words;
    while (getline(in, line))
        words.push_back(line);
    in.close();

    for (auto i : words)
    {
        string word;
        istringstream ist(i);
        while (ist >> word)
            cout << word << endl;
    }
    return 0;
}
//习题8.11

struct PersonInfor
{
    string name;
    vector<string> phones;
};
int main()
{
    vector<PersonInfor> people;
    string line, na;
    istringstream record;
    while (getline(cin, line)) {
        PersonInfor info;       
        record.clear();//notice重复使用字符串流时每次都要clear
        record.str(line);
        record >> info.name;
        while (record >> na)
            info.phones.push_back(na);
        people.push_back(info);
    }
}
//习题8.13电话号码程序--出错原因:main函数读取的文件有问题
//忘了将文件放在exe同名文件夹,而是放在了main函数的文件夹
//运行时用命令行打开,如text.exe 1.txt即可打开。
struct PersonInfo
{
    string name;
    vector<string> phones;
};
string format(const string &s) 
{
    return s; 
}
bool valid(const string &s) 
{
    //此处简单返回true,后续再改
    return true;
}
//int main()

int main(int argc, char *argv[])
{
    string line, word;
    vector<PersonInfo> people;
    istringstream record;
    if (argc != 2) {
        cerr << "请给出文件名" << endl;
        return -1;
    }
    ifstream in(argv[1]);
    if (!in)
    {
        cerr << "无法打开文件" << endl;
        return -1;
    }
    while (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);
    }
    ostringstream os;   
    for (const auto &entry : people) {
        ostringstream formatted, badNums;
        for (const auto &nums : entry.phones) {
            if (!valid(nums)) {
                badNums << " " << nums;
            }
            else
                formatted << " " 
                << format(nums);//????????????????
            if (badNums.str().empty())
                os << entry.name << " " 
                << formatted.str() << endl;
            else
                cerr << "input error : " << entry.name 
                << " invalid number(s) " 
                << badNums.str() << endl;
        }
        cout << os.str() << endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值