Search txt file...

In the searchPhoneNumber i want to the user to type in Company name and if found display number and what line it was found on! If not found output "not found" Please HELP - i'm so nooob at this...

--------------------------------
#include "stdafx.h"
#include "iostream"
#include "fstream"
#include "string"
using namespace std;

void addPhoneNumber()
{
int rows=10,col=2;
string **tel=new string*[rows];
for(int i=0; i<rows; i++)
{
tel[i]=new string[col];
}
flushall();
for(int i=0; i<rows; i++)
{
cout<<"Enter Company : ";
getline(cin,tel[i][0]);

cout<<"Enter Telephone : ";
getline(cin,tel[i][1]);
}
ofstream write("telephone.txt",ios::app);
for(int i=0; i<rows; i++)
{
write<<tel[i][0]<<endl;
write<<tel[i][1]<<endl;
}
write.close();
}

void searchPhoneNumber()
{


}


void menu()
{
char ch;
do{
system("cls");

cout<<"\n1: Add new phonenumbers\n";
cout<<"\n2: Search for phonenumber \n";
cout<<"\n3: Exit\n";

int choice;
cout<<"\nEnter you choice : ";
cin>>choice;

switch(choice)
{
case 1:
{
addPhoneNumber();
break;
}
case 2:
{
searchPhoneNumber();
break;
}
case 3:
{
exit(1);
break;
}
default:
{
cout<<"\nWrong choice\n";
break;
}

}

cout<<"Do you want to continue (y/n) : ";
cin>>ch;

}while(ch=='y'||ch=='Y');

}

void main()
{
menu();
system("pause");
}
Last edited on
what do you mean when you say that itmust display number, what number???
what is the logic beyond your whole program?
Telephone number....
Its just a example...
Can you help?
You'd need to open a stream to the file using ifstream fs(filename)
Then you would do something along these lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
int lineNum = 0;
string line;
string correctPhoneNumber;
while(getline(fs,line))
{
    if(line == company)
    {
         getline(fs, correctPhoneNumber);
         cout << "The company's number is "<< correctPhoneNumber << " found at line " << (lineNum+1);
         break; 
    }
    lineNum++;
}


The method I've given is based on how your addNumber worked. Personally I'd have company name and number on the same line separated by a ';' rather than having them on separate lines.

Also avoid using system, it's generally not good practice: http://www.cplusplus.com/articles/j3wTURfi/

Topic archived. No new replies allowed.