-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathysum.cpp
58 lines (52 loc) · 1.07 KB
/
ysum.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
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
// assume sorted
ifstream ifs;
istream *pis = NULL;
if( argc == 2 )
{
ifs.open(argv[1]);
pis = &ifs;
}
else if( argc == 1 )
{
pis = &cin;
}
if( argc > 2 )
{
cerr << "Too Many Arguments.\n";
return 1;
}
if( !pis->good() )
{
cerr << "Can not Open File.\n";
return 1;
}
string line;
string item, lastItem;
unsigned long long cnt=0, sumCnt=0;
while(getline(*pis, line))
{
stringstream ss(line);
ss >> item >> cnt;
if(item == lastItem)
{
sumCnt += cnt;
}
else
{
if( sumCnt >= 0 && !lastItem.empty() )
cout << lastItem << "\t" << sumCnt << "\n";
sumCnt = cnt;
lastItem = item;
}
}
if( sumCnt >= 0 && !lastItem.empty() )
cout << lastItem << "\t" << sumCnt << "\n";
return 0;
}