Search code examples
c++ifstream

C++ Reading from a file given by user


I'm creating a simple directory program that allow user to enter a file name and search that file by name, address, or phone number. I'm having trouble properly reading the file.

If someone could give me suggestions on how to fix my getFirstName function. The function should read the first word of the file.

Example file:

Bob Smith 123456789
123 Main Street
Susan Smith 1224445555
543 Market Street

Here is part of my code so far.

 string file;
 string first;
 int main() {
     ifstream inFile;
     cout<<"Enter file name: ";
     cin>> file;
     inFile.open(file);
     if(inData.fail()) {
         cout<<"INVAILD";
     }
     getFirstName(first);
}

void getFirstName(string f, inFile file) {

    file.open(f);
    while(file.good(f)) {
        file>>f;
    }
    if (file.bad()) {
        cout<<"Name not found";
    }
}

Solution

  • i will not write you the program, but let me point you in a direction.

    first of all: please format your code better. maybe its just because stackoverflow, but there should be consistent and sensefull formatting of your code, otherwise you and others cant read it well and have trouble finding problems. (plz google clang-format for a tool, maybe an ide would do it as well).

    split your programm in different logical parts. my approach would be:

    1. open file, if not possible give warning, end program
    2. read file content into a string IN: filename, OUT: string of content
    3. split the string into line, IN: string, OUT: std::vector
    4. for each line, split the line into parts(3 elements?) IN: linestring, OUT: name, street, ...
    5. You can that in proper datastructures, plz see the STL for good ones
    6. Access your datastructure for the wanted information.

    Proposal for your data.

    • istream for file, you have that
    • std::string for file content
    • std::vector for line wise filecontent
    • std::unordered_map map the name to information.

    this should give you a googling start. each subproblem can be solved independent (and tested) and is easier to find on SO :)

    Good luck.