Reading data from text file

Hello friends,
I am working on my class project, In which I have to read a text file with character separated by integer. Following is the format of the file:
I 23
I 67
I 89
D 23
F 89
I 62
I-Insert D-Delete and F-Find
After reading the text file, I need to perform the operations on binary search tree as directed.
I can write the program for insertion, deletion and find. The only problem I am facing here is how to get this data from file and check weather it is 'I', 'D' or 'F' and then perform the operation accordingly.
Could anybody help me please.
Following is the code I wrote for reading the data from file.

string s;
ifstream myfile("xyz.txt");
if(myfile.is_open()){
while(getline(myfile,s))
{
cout<<s<<endl;
}
myfile.close();
}
else cout<<"Unable to open file";
return 0;
}
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
#include <iostream>
#include <fstream>
#include <cctype>

int main()
{
    const char* const file_name = "xyz.txt" ;
    // create a test file
    { std::ofstream(file_name) << "I 23 \n I 67 \n I 89 \n D 23 \n F 89 \n I 62 \n" ; }

    std::ifstream file(file_name) ; // open the file for input

    if( file.is_open() )
    {
        char operation ;
        int value ;
        while( file >> operation >> value ) // for each operation,value pair read from the file
        {
            switch( std::toupper(operation) )
            {
                case 'I' : std::cout << "insert " << value << '\n' ; break ;
                case 'D' : std::cout << "delete " << value << '\n' ; break ;
                case 'F' : std::cout << "  find " << value << '\n' ; break ;
                default  :  std::cout << "invalid operation '" << operation << "'\n" ;
            }
        }

        if( file.eof() ) std::cout << "\nentire file was processed\n" ;
        else std::cerr << "\nbadly formed input: remaining lines were ignored\n" ;
    }

    else std::cerr << "could not open file '" << file_name << "' for input\n" ;
}

http://coliru.stacked-crooked.com/a/3e0cb995943f069f
Topic archived. No new replies allowed.