C++ Array. Counting the number of instances?

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
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
  int ctr = 0;
  const int AR_SIZE = 10;
  string names[AR_SIZE];

  for (ctr = 0; ctr < 10; ++ctr)
  {
    cout << "Enter name #" << ctr + 1 << ":";
    getline(cin, names[ctr]);
  }

  string searchnames;

  cout << endl << "Who do you want to search for (enter done to exit)? ";
  getline(cin, searchnames);

  int instances;
  instances = 0;
  int itemcount;
  itemcount = 10;



  while (searchnames != "done")
  {
    int search = 0;
    for (search = 0; search < 10; search++)
    {

      if (names[search] == searchnames)
      {

        instances++;

      }
    }

    if (instances > 1)
    {
      cout << "There are " << instances << " instances of the name " <<
        searchnames << "." << endl;
    }

    else if (instances == 0)
    {
      cout << searchnames << "'s" << " name does not exist in this list."
        << endl;
    }

    else if (instances == 1)
    {
      cout << "There is one instance of the name " << searchnames << endl;
    }



    cout << endl << "Who do you want to search for (enter done to exit)? ";
    getline(cin, searchnames);


  }



  return 0;
}




The problem I'm having is when it outputs the number of instances. It will add the amount of instances each time you search a new name. What it should do is say you enter Joe 3 times and Sally once, and Don 6 times and, Mark none. You search for Joe it should say "There are 3 instances" You search Sally it should say "one instance" Search for Mark it should say "Does not exist.

What it's doing though is adding the number of instances up each time
Figured out what I did wrong.

I should of set instances back to 0 at the top of the while loop.
Do you realize that you can initialize and declare simultaneously?
1
2
int instances(0);
int itemcount(10);


Also you could use std::count to simply your code and avoid common mistakes that are sometimes made within loops. Your loop looks fine in that case but it is better to prefer std algorithms over hand written loops. Notice that when using std::count there is no need to reset the instance variable since you aren't the one incrementing it. It simply gets reassigned a new value for each call of std::count thus avoiding the error that you found.
Replace
1
2
3
4
5
6
7
for (search = 0; search < 10; search++)
{
    if (names[search] == searchnames)
    {
        instances++;
    }
}


with
1
2
// count returns ptrdiff_t which is a signed integral type, hence the static_cast<int>
instances = static_cast<int>(std::count(names, names + AR_SIZE, searchnames);
Last edited on
Topic archived. No new replies allowed.