-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex8_5.cpp
53 lines (48 loc) · 1.1 KB
/
ex8_5.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
/**
* Exercise 8.4: Write a function to open a file for input and read its contents
* into a vector of strings, storing each line as a separate element in the
* vector.
* Exercise 8.5: Rewrite the previous program to store each word in a
* separate element.
*/
#include <fstream>
#include "iostream"
#include "vector"
#define SIMPLE
int getw(std::string &, std::istream &);
int main(int argc, char **argv) {
if (argc == 1) {
std::cout << "usage: " << *argv << " FILE PATH" << std::endl;
return -1;
}
std::ifstream ifs(*++argv);
if (!ifs) {
std::cout << *argv << ": read failed." << std::endl;
return -1;
}
std::vector<std::string> vword;
std::string buf;
#ifndef SIMPLE
while (getw(buf, ifs)) {
vword.emplace_back(buf);
buf.clear();
}
#else
while (ifs >> buf)
vword.emplace_back(buf);
#endif
/// print
for (auto beg = vword.begin(); beg != vword.cend(); ++beg)
std::cout << *beg << std::endl;
}
int getw(std::string &s, std::istream &is) {
int n = 0;
int c;
while (isspace(is.get())) ;
is.unget();
while ((c = is.get()) != EOF && !isspace(c)) {
++n;
s.push_back(c);
}
return n;
}