-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPage323_osstream.cpp
90 lines (89 loc) · 2.37 KB
/
Page323_osstream.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using std::cout;
using std::cin;
using std::cerr;
using std::endl;
using std::istringstream;
using std::ostringstream;
using std::string;
using std::vector;
struct PersonInfo {
string name;
vector<string> phones;
};
bool valid(const string& s)
{
int size = 0;
for(auto &c : s)
{
if(!isdigit(c) && c != ' ' && c != '-')
return false;
if(isdigit(c))
++size;
}
if(size == 11 || size == 12 || size == 8)
return true;
else
return false;
}
string format(const string& s)
{
string num;
for(auto ch : s)
{
if(isdigit(ch))
num += ch;
}
return num;
}
int main()
{
string line, word; // will hold a line and word from input, respectively
vector<PersonInfo> people; // will hold all the records from the input
istringstream record; // move istringstream here
ostringstream os;
// read the input a line at a time until cin hits end-of-file(or another error)
while(getline(cin, line))
{
PersonInfo info; // create an object to hold this record's data
record.clear(); // WARNING: without this, we can only read one record, because after the first
// iteration, fail and eofbit will be set
record.str(line); // copy a line we just read to record
if(record.eof())
cout << "record eof" << endl;
if(record.fail())
cout << "record fail" << endl;
record >> info.name; // read the name
while(record >> word) // read the phone numbers
info.phones.push_back(word); // and store them
people.push_back(info); // append this record to people
}
for(const auto &entry : people)
{
os.clear();
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;
cout << os.str();
}
else
cerr << "input error: " << entry.name
<< " invalid number(s)" << badNums.str() << endl;
}
return 0;
}