Hello,
Below is my code for Reading, Finding, and Converting strings from Text file, which is a project to my class in C++.
The project is divided into 3 major parts.
1. Read text from file (ifstream).
2. Remove comma from text file that separates the records (strtok).
3. Search Record from text file. (strcmp).
My project is running with no errors, as you can check the code below. The only thing that my professor found that little mistake, is that when I entered a non-existing ID number, the program "must" tell something like "Record NOT found." I don't know where to add it. Thank you for those who can give me the location where to put the
cout << "Record Not FOUND"; line. :)
FYI: I use devC++ UI; C++ code are written by me, thanks to cplusplus.com References. :)
Use this dummy text below, paste in notepad or other text editor and save it as "sample.txt"
001,John,Doe
002,Lady,Doll
003,Princess,Star
004,Allen,Smith
I really need your help. Thank you very much in advance. :)
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
|
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
string buffer;
char id[100];
string fname,lname;
int find=0;
start:
cout << "Find ID: ";
cin >> id; //accepts user input for ID
ifstream data("sample.txt");
if(!data.is_open())
{
cout << "File is already opened.";
}
else
{
while(!data.eof())
{
getline(data, buffer);
char *newstr = new char [buffer.length()+1];
strcpy(newstr, buffer.c_str());
char *ch = strtok(newstr, ",");
int x=1;
while(ch!=0)
{
find=strcmp(newstr, id);
if(find==0)
{
if(x==1) cout << "ID Number: ";
else if(x==2) cout << "First Name: ";
else if(x==3) cout << "Last Name: ";
cout << ch << endl;
x++;
} //<-------closing find IF
ch = strtok(NULL, ",");
//if(data.eof()) cout << "Record Not found."; <<< currently not working
} //<-------- closing ch WHILE
} //<--------closing data.eof WHILE
data.close();
cout << endl;
goto start;
}
system("PAUSE");
return EXIT_SUCCESS;
}
|