Phone Directory

I have a lot of code right now but I did it wrong...I need to be able to put the phone number in and the name is output. I have it reversed I think but when I try to change it I get build errors. This is what I have
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
#include <iostream> 
#include <cstdio> 
using namespace std; 
 
int main() 
{ 
  int i; 
  char str[80]; 
  char numbers[10][80] = { 
    "Tom Smith", "555-3322", 
    "Mary Smith", "555-8976", 
    "Jon Smith", "555-1037", 
    "Rachel Smith", "555-1400", 
    "Sherry Smith", "555-8873" 
  }; 
 
  cout << "Enter phone number: "; 
  cin >> str; 
 
  for(i=0; i < 10; i += 2)  
    if(!strcmp(str, numbers[i])) { 
      cout << "Number is " << numbers[i+1] << "\n"; 
      break; 
    } 
   
  if(i == 10) cout << "Not found.\n"; 
   
 
  return 0; 
}
I'm confused as to how I alter the "cin" under Enter Phone Number and the cout where it says Number is. I know I should change it to Name is but I don't know what to put after that to make it so that when I enter the phone number it outputs the name.
I think you might want to make this easier on yourself and learn how to use std::map (http://www.cplusplus.com/reference/map/map/).

A std::map is an STL data type that holds associates two values by having a value and a key to that value. In other words, you could store the name as the value and use the phone number as the key (or vice versa). Here is an example:

1
2
3
4
5
6
7
8
// Create an empty std::map with a string type key and string type value.
map<string, string> phone_book;

// Store the value "Tom Smith" behind the key "555-3322"
phone_book["555-3322"] = "Tom Smith";

// Now I can simply do this to print the name behind the number.
cout << phone_book["555-3322"] << endl;


The output would look like this.
Tom Smith


Now, I say all of this assuming that you're allowed to use whatever you wish. If this is a homework assignment and you are only allowed to use character arrays then that's a different story.

Hope this helps!
Cheers,
Tresky

EDIT: Added link to documentation.
Last edited on
Topic archived. No new replies allowed.