problem with searching name in file in c++

i have to write a c++ code for telephone directory in which a user can search for number for specific name given. i have written this code but isn't working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  void dir::fNum()
{
     cout<<"enter the name for which you want to search number :"<<"\t";
     cin>>name;
     ifstream a3;
     string line1,line2;
     a3.open("telephone", ios::in);
     if(!a3)
     cout<<"can not open the file";
     else
     {
         while(getline (a3,line1))
         {
                       if(sizeof(line1)==sizeof(name))
                      { cout<<"record found"<<endl;
                        cout<<"\t"<<line1<<"\t"<<line2<<endl;
                       }
                       else
                       cout<<"record not found";
         }
         a3.close();
     }
    }
    
Is it not doing what's intended, or not compiling?
I can't help much without know the rest of the system.

I would have a struct containing the name string and the number. Create an array of these structs and initialize them through loop and record the amount of structs received if that makes sense.

Something like,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

bool ReadDirectory(char* cDirName)
{
        std::ifstream ifs(cDirName);
        if(!ifs) return 0; // Error, file could not be read

        std::string name; int number; int counter;
        counter = 0;
        while() // Your paramteres
        {
                ifs >> DataStruct[counter].name; ifs >> DataStruct[counter].number;
                if(name == "") return 0; // All data has been read
                counter++;
        }
        return 1;
}




Then to search for the names you can loop through the array and check for the name:

1
2
3
4
5
6
7
8
bool CheckData(std::string name)
{
        for(int i = 0; i < MaxData; i++)
        {
                if(Data[i].Name == name) return 1; // Name found
        }
        return 0; // Name was not found
}



Other than that I cannot help you further without knowing more.
sorry for the inconvenience.. my code is not able to search the stored record. it always shows record not found..
here is the complete code
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>

using namespace std;

class dir{
      char name[20], num[6];
      public:
             void get();
             void show();
             void fNum();
      };
      
void dir::get()
{
     ofstream a1;
     a1.open("telephone", ios::out|ios::app);
     if(!a1)
     cout<<"can not open file ";
     else{
     cout<<"enter the name :"<<"\t";
     cin>>name;
     cout<<"enter phone number :"<<"\t";
     cin>>num;
     a1<<name<<setw(20)<<num<<endl;
     a1.close();
     }
     }
     
void dir::show()
{
     string line1,line2;
     ifstream a2;
     a2.open("telephone", ios::in);
     if(!a2)
     cout<<"can not open file";
     else
     {
         cout<<"\t Records in phone book are"<<endl;
          while(getline (a2,line1))
         cout<<"\t"<<line1<<"\n";
                   a2.close(); 
         }
     }
     
void dir::fNum()
{
     cout<<"enter the name for which you want to search number :"<<"\t";
     cin>>name;
     ifstream a3;
     string line1,line2;
     a3.open("telephone", ios::in);
     if(!a3)
     cout<<"can not open the file";
     else
     {
         while(getline (a3,line1))
         {
                       if(sizeof(line1)==sizeof(name))
                      { cout<<"record found"<<endl;
                        cout<<"\t"<<line1<<"\t"<<line2<<endl;
                       }
                       else
                       cout<<"record not found";
         }
         a3.close();
     }
    }
     
int main()
{
    int z,i;
    dir d1,d2;
    cout<<"welcome.."<<endl;
    cout<<"1. Add a new record"<<endl;
    cout<<"2. Display all records"<<endl;
    cout<<"3. Find number for a specific name"<<endl;
    cout<<"4. Find name for a specific record"<<endl;
    cout<<"5. Update a record"<<endl;
    cout<<"6. Exit."<<endl;
    cout<<"Enter your choice"<<endl;
    cin>>i;
    switch(i)
    {
             case 1:
                  d1.get();
                  break;
             case 2:
                  d1.show();
                  break;
             case 3:
                  d1.fNum();
                  break;
             }
    cin>>z;
    return 0;
    }
From what you have shown me I'd really rework that system. If you're professor has taught you to store numbers in a char array I am ashamed to be a programmer.

1
2
3
4
5
6
7
class dir{
      char name[20], num[6];
      public:
             void get();
             void show();
             void fNum();
      };


I would sort this into:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Data
{
      std::string FirstName; // Store first name
      std::string LastName; // Store last name
      int TelephoneNumber; // Store telephone number
};

class Directory
{
public:
          Directory(){}
          Directory(const char* dir) {} // File to open
          ~Directory() {}
          void LoadDirectory(const char* n) {} // New directory file to load
          Data& GetRecord(int s) { return d[s]; } // Get data at slot s
private:
        Data d[100]; // Stores 100 records of firstname, lastnames and numbers.
};



Look a little more into program control, the problem is your design.
okay but if i use int data type then it may exceed the range of integers, that's why i took array of characters for number.
There is LL and ULL too, for couple extra digits.

However, if there are more digits and you need to calculate anything with those numbers later, then you have to face the string->numeric conversion at some point.

Look up some third-party libraries (e.g. Boost) that already offer "BigInt" types for managing huge numbers. That wheel has been invented.

Then again, a phone-number is not a number. At least, it is not a simple number; there is country code, area code, and whatnot.


The std::string is superior to array of characters in almost every case.
thanks but can you tell me the data type?
thanks but can you tell me the data type?


A std::string would be my recommendation, along with replacing all your other C-strings with std::string. The std::string class has many functions to aid in comparing strings.

okay but if i use int data type then it may exceed the range of integers, that's why i took array of characters for number.


You are right yes, so check it?

 
if(TelephoneNumber) > 999999 || TelephoneNumber < 0) std::cout << "ERROR: Invalid number - Invalid digits\n";



You are right yes, so check it?

If you're using an int you can't check to see if the user entry is within range of an int, it's too late you're already in Undefined Behavior land.

The safest way of getting user input is to get the input into a std::string then parse that string to insure the values are acceptable.

Also many people expect to see "punctuation" used for telephone "numbers", ie "1-800-345-9123" or "+44-207xxxxxxx"
Last edited on
1
2
3
4
5
6
7
8
9
10
11
if(!std::cin >> TelephoneNumber)
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<int>::max(), '\n'); // Incorrect data received?
}
else
{
    if(TelephoneNumber) > 999999 || TelephoneNumber < 100000) std::cout << "ERROR: Invalid number - Invalid digits\n"; // Proper data entered though not in range of number?
}

Ignore apparently wrong.


I would use a stringstream for a punctuated number.

I would also guarantee the safest way to get user input is if the user knows what to input rather than guess.

1
2
std::cout << "Please enter a number in the format: XXXXXX\n"
std::cout << "Please enter a number in the format: +AC-XXX-YYY\n" // I find that strange way to store a number, but that's me. 
Last edited on
Your snippet doesn't solve the problem of the user entering a value that is greater than what can safely be held in an int. The stream will accept any number from the user and try to store that number into your int variable. If the value is larger that what can safely be held in the type it doesn't cause a stream error, it just invokes undefined behavior.


I find that strange way to store a number, but that's me.

That's because a "Telephone number" is not a number, it is a series of "numbers", actually a series of digits. Every digit in the sequence means something. Also remember that when you start having a large number of digits without any separation it gets harder and harder for us humans to read the numbers. That's why even when dealing with actual numbers humans usually add punctuation to make things easier to read Ie 100,000,000,000 .

Last edited on
Right, so instead you would use a string and check it for what? The limits of an int?

That's because a "Telephone number" is not a number, it is a series of "numbers", actually a series of digits. Every digit in the sequence means something.

Also remember that when you start having a large number of digits without any separation it gets harder and harder for us humans to read the numbers. That's why even when dealing with actual numbers humans usually add punctuation to make things easier to read Ie 100,000,000,000 .



Does a computer see a series of numbers the same as we do? Perhaps I am misunderstanding.

EDIT: I don't want to jack this thread. If you want to continue this PM me.
Last edited on
Right, so instead you would use a string and check it for what?

This is why getting input from the user is problematic, there is no easy way to accomplish this task. But it can be done by comparing the number of digits of the entered value to the maximum number of digits of the largest allowable number of the type. If the entered value has fewer digits than the maximum you can safely convert the string to your number. If the entry has more digits than the maximum then you can't accept the number, inform the user and take some action. But if the number of digits entered is equal to the number of digits in the maximum you'll need to do more work.

Does a computer see a series of numbers the same as we do?

No, a computer only sees binary, 0 or 1, and the computer doesn't need any "punctuation".

But remember we design the computer interface to make it easier for humans, not the computer.

No, a computer only sees binary, 0 or 1, and the computer doesn't need any "punctuation".


That is why I design data a computer can understand, and the interface something a human can understand. In his example he is trying to read in data from a file and store it into memory, this is separated from the interface, I believe. It's hard to pinpoint how this should be done without knowing how the file is encoded in the first place.

When you want to print this number to the screen sure add as many dots, dashes and asterisks to your hearts content. In my humble opinion, computer data should be separated from human readable data.

At the end of the day people do things differently, he/she may not even do it our way. That's the beauty of programming.



Also I like how you say
No, a computer only sees binary, 0 or 1.
like I don't know. :) The question was to show no matter how data is encoded a computer will see it in the same way as any other piece of data on the system, the difference is how it is perceived.

Even better if people knew how to use the program and to input the correct data, we wouldn't even need all this!
I haven't read all this, but to answer your question, I notice you keep using a construct something like this:

1
2
3
4
5
6
string line1;
string name;

...

if (sizeof(line1) == sizeof(name)) ...

I don't know who taught you that sizeof() thing, but it isn't doing what you think it is. That returns the number of bytes used by an object. In the case of two std::string objects, the number of bytes used by them is the same -- no matter what string data you have managed by it.

If you want to compare two strings, use:

if (line1 == name) ...

Hope this helps.
Topic archived. No new replies allowed.