#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Pair{ string name; double val;};
vector<Pair> pairs;
double& value(const string& s)
{
for(unsigned int i=0; i < pairs.size(); i++)
if(s==pairs[i].name) return pairs[i].val;
Pair p={s,0};
pairs.push_back(p);
return pairs[pairs.size()-1].val;
}
int main()
{
string buf;
while(cin>>buf) value(buf)++;
for(vector<Pair> :: const_iterator p= pairs.begin(); p != pairs.end
();++p)
cout <<p->name << " : "<<p->val <<"\n";
return 0;
}
> hello
> here is code from "The C++ Programming langauge" by Bjarne Stroustrup.
> the code is working but not showing the output when press ctrl+c it
> shows only interrupt and first input.
> wht's wrong with this code.
There's nothing wrong with it. Press CTRL-D instead of CTRL-C.
~/data/CPP/SSC++ $ g++ -Wall -Wextra -ansi -pedantic ex-5-4-1.cpp
~/data/CPP/SSC++ $ ./a.out
aa
bb
aa
bb
aa
aa
bb // press Ctrl+D
interrupt
is there something wrong
and i am confused with
while(cin>>buf) value(buf)++;
why increment ?
.........
I think you should first understand some basic things of C/C++ before
moving on to topics like vector etc.
The question "why increment ?" tells me that you're a beginner. So
move on slowly.
Start your book from the beginning and try again.
Greetings
That seems ok. Worked for me.
> aa
> bb
> aa
> bb
> aa
> aa
> bb // press Ctrl+D
> interrupt
Do you mean that you don't get the list of frequencies at
the end? i.e.,
aa: 4
bb: 3
That seems odd... but I would think it has less to do with
your program than your OS, or the particular terminal
application you're using.
> and i am confused with
>
> while(cin>>buf) value(buf)++;
> why increment ?
It's counting the number of times each input string is
typed. "value()" returns a reference to "number of times
'buf' has been typed". Then that number is incremented.
--Jonathan
yes
> That seems odd... but I would think it has less to do with
> your program than your OS, or the particular terminal
> application you're using.
using gcc 4.4.2
> It's counting the number of times each input string is
> typed. "value()" returns a reference to "number of times
> 'buf' has been typed". Then that number is incremented.
Thanks...
Or some other system specific sequence. (Under Windows, it's
CTRL-Z.) Fundamentally, end of file doesn't exist for a
keyboard: Unix sort of simulates it if you enter CTRL-D at the
beginning of the line (supposing no ones been playing around
with stty); traditionally, Windows library software considers
CTRL-Z an end of file in any text file.
And both agree about CTRL-C: terminate the program doing the
input, or all programs in the "terminal group" under Unix. (But
the program can catch the signal, and not die, and of course, if
you've let someone else get at your terminal while you're logged
in, and they've played around with stty, who knows what may
happen.)
--
James Kanze