is this a string bug?

Kate Hedstrom kate@ahab.rutgers.edu
Tue Oct 28 15:58:00 GMT 1997


In chapter 5 of the new Stroustrup edition there is the program
shown below.  It produces:

> ahab% a.out
> aa bb aa bb aa cc  <return><ctrl-D>
> cc: 6

while Bjarne says it should produce:

   aa: 3
   bb: 2
   cc: 1

In the debugger you can see that buf (and s) becomes the same string as
the string in pairs[0] so the "if (s == pairs[i].name)" comparison is
always true after the first time through.  This is with:

ahab% gcc -v
Reading specs from
/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/egcs-2.90.10/specs
gcc version egcs-2.90.10 970924 (gcc2-970802 experimental)

and also a newer egcs on my home computer.


ahab% more pairs.cc
#include <iostream.h>
#include <vector.h>
#include <string>

struct Pair {
    string name;
    double val;
};

vector<Pair> pairs;

double& value(const string& s)
/*
 * maintain a set of Pairs:
 * search for s, return its value if found; otherwise make a new Pair
 * and return the default value 0
 */
{
    for (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';
}



More information about the Gcc mailing list