I am currently a beginner in C++; I'm working on a small task to write a program that prompts the user for a last name then searches a file named book.data and prints out the phone numbers of all entries with that last name. I have made the text file already, so my problem is that I cannot get the program to search the file the entries with the specific letter pertaining to the users input.
Here's what I have:
1 #include <iostream>
2 #include <fstream>
3 #include <string>
4 using namespace std;
5
6 int main () {
7
8 string phone_book;
9 string lastName; // users last name
10 ifstream myfile ("book.data.txt");
11
12 cout << endl << "Enter your last Name" << endl;
13 cin >> lastName;
14
15 if (myfile.is_open()) {
16
17 while(myfile.good()){
18
19 getline(myfile, lastName); // reading book.data
20 cout << lastName << endl;
21 }
22
23 myfile.close();
24
25 }
26
27 else cout << endl << "Unable to open Phone Book" << endl;
28
29
30 return 0;
31 }
My goal is to print out all the last names that the user inputed. For example the letter "G", my program doesn't print out a list of last names with specifically with the letter G, but rather all the last names.
i am pretty new at this too but you need to get the user input and assign it to a var then do a loop to compare it to your data, them if name in == data then cout your data file. you can use string stream for input and convert to a char array to capture the first letter. let me know if that is more confusing or helpful.
Dear Chervil, I've made the changes, thank you! My text file book.data currently contains information such as last name, first name, followed by address & tel. per line, it's a dummy phone book.
-Lazysquirell, I think I understand..you're suggesting to create an array?
I've not tested this, so there may be mistakes. It tries to search each line for the name entered by the user. If it is found starting at the first character position, display that line.