Linear search

hi....im new to C++ and still getting a lot of problems understanding how it really works

1. i need to search a text file with records of music albums by the name of the album and display the information of that album in a formatted way

2. secondly i also need to search the file so that i can delete only 1 album of choice

here is what i managed to do till now

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

void do_again(),direction(int ans);
void option_1(),option_2(),option_3(),option_4(),option_5(),option_6();
void choice_1();

struct item
{
string name,artist,category;
int stock;
float price;
int count;
item *nxt;
};

item *p=NULL;
item *current;

int main()
{
do_again(); //call do_again function, say goodbye to main until everything else is done running

return 0;
} //end function

void do_again()
{
int ans; //declare ans variable, this will be used OVER AND OVER
do
{
cout << "\t\t\t\t Main Menu\n";
cout << "\t\t\t\t ---------\n\n";
cout << " *******************************************************************\n";
cout << " * *\n";
cout << " * Add a new album ......................................... [1] *\n";
cout << " * *\n";
cout << " * Search for a particular album ........................... [2] *\n";
cout << " * *\n";
cout << " * Delete an album ......................................... [3] *\n";
cout << " * *\n";
cout << " * Print all albums ........................................ [4] *\n";
cout << " * *\n";
cout << " * Sales ................................................... [5] *\n";
cout << " * *\n";
cout << " * Exit .................................................... [6] *\n";
cout << " * *\n";
cout << " *******************************************************************\n";
cout << "\n -> Enter Selection : ";

cin >> ans;
cin.ignore(80,'\n'); //take in an answer
direction(ans); //send that answer to direction!
}

while(ans!=6); //keep on keepin on till they pick exit!
} //end function

void direction(int ans)
{
switch (ans) //roll through options
{
case 1: option_1(); //go to function 1
break;
case 2: option_2();
break;
case 3: option_3();
break;
case 4: option_4();
break;
case 5: option_5();
break;
case 6: option_6();
break;
default: cout << "Please read and follow all directions\n"; //if directions aren't followed
break;
}
} //end function

//Functions

void option_1()
{
system("CLS");

item *list,*temp2;

list = new item;

cout<<"Album details\n";
cout<<"-------------\n\n";

cout<<"Album Name: ";
getline(cin, list->name);

cout<<"Album Artist: ";
getline(cin, list->artist);

cout<<"Category: ";
cin>>list->category;

cout<<"Amount Bought: ";
cin>>list->stock;

cout<<"Price: ";
cin>>list->price;


list->nxt=NULL;

if (p == NULL)
{
p = list;
current=p;
}
else
{
temp2 = p;

while (temp2->nxt != NULL)
{
temp2 = temp2->nxt;
}
temp2->nxt = list;


}

item *temp;
temp = p;

ofstream f;
f.open("database.txt", ios::app);

do
{
f<<"Album Name : " <<temp->name<<endl;
f<<"Album Artist : " <<temp->artist<<endl;
f<<"Category : " <<temp->category<<endl;
f<<"Amount in Stock : " <<temp->stock<<endl;
f<<"Price : " <<temp->price<<endl;
f<<"----------------------------------";
f<<"\n\n";
temp = temp->nxt;
}
while (temp != NULL);
f<<endl;

// displaying item entered
cout<<"\nAlbum " << list->name<<" added successfully.\n\n";

f.close();

choice_1();

system("CLS");

}//end function

void option_2()
{
}//end function

void option_3()
{
}//end function

void option_4()
{
system("CLS");

string line;

ifstream f("database.txt");
if (f.is_open())
{
while (! f.eof() )
{
getline (f,line);
cout << line << endl;
}
f.close();

system("pause");
system("CLS");
}

else cout << "Unable to open file";
}//end function

void option_5()
{
}//end function

void option_6()
{
}//end function

void choice_1()
{
char ans;

cout<<"Do you want to enter another item?(y/n)";
cin>>ans;
if(ans=='Y' || ans=='y')
{
option_1();
}

if(ans=='N' || ans=='n')
{

}

else
{
cout << "\nWrong choice!!\n\n";
choice_1();
}
}


PLEASE HELP!!
This should work for option2. (searching)
Make sure to include <sstring>.
I Hope you learn from this example.

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
64
65
66
67
68
69
70
71
72
73
74
75
void option_2()
{
    system("CLS");
    ifstream in_file("database.txt");
    if (!in_file.is_open()) {
        cerr << "Error: could not find database.txt" << endl;
        return;
    }
    // read album name to look for
    item album_info;
    cout << "Album Name: ";
    if (!getline(cin, album_info.name)) {
        cerr << "Error while reading from keyboard.\n";
        cin.clear();
        return;
    }
    // read line for line as long no error occurs
    string line;
    while (getline(in_file, line)) { 
        size_t pos = line.find(album_info.name);
        if (pos == string::npos) {
            continue;
        }
        // if you pass here, you found your album by name
        
        const string kPrefixAlbumLines[] = { 
            "Album Artist : ",
            "Category : ",
            "Amount in Stock : ",
            "Price : "
        };
        string album_lines[4];
        for (int i = 0; i < 4; i++) {
            if (!getline(in_file, album_lines[i])) {
                cerr << "An error occured while reading from file.\n";
                return;
            }
            album_lines[i].erase(0, kPrefixAlbumLines[i].length());
        }
        album_info.artist   = album_lines[0];
        stringstream converter;
        
        converter.str(album_lines[1]);
        if (!(converter >> album_info.category)) {
            cerr << "Corruped data entry in category field!\n\n";
        }
        converter.str(album_lines[2]);
        converter.clear();
        if (!(converter >> album_info.stock)) {
            cerr << "Corruped data entry in stock field!\n\n";
        }
        converter.str(album_lines[3]);
        converter.clear();
        if (!(converter >> album_info.price)) {
            cerr << "Corruped data entry in price field!\n\n";
        }
    }
    in_file.close();

    // format your output as you wish. Maybe you should define an << operator to ostream for
    // your info structure.
    // if you keep output like this, it would be easier to print lines directly. With this method you
    // can change the values of the info struct and blablah
    cout << endl << endl;
    cout << "Album Name : "      << album_info.name     << endl;
    cout << "Album Artist : "    << album_info.artist   << endl;
    cout << "Category : "        << album_info.category << endl;
    cout << "Amount in Stock : " << album_info.stock    << endl;
    cout << "Price : "           << album_info.price    << endl;
    cout << "-------------------------";
    cout << "\n\n";
    
    cin.get();
    system("CLS");
} //end function 



Maikel
Last edited on
hey thnx 4 ur help Maikel

i included the <sstring> as u said but still i get the error message

1
2
3
sstring: No such file or directory.
In function 'void option_2()';
aggregate 'std::stringstream converrter' has incomplete type and cannot be defined
Oups, my mistake:

 
#include <sstream> // string stream 
hey it works :D
thanx a lot man.....ur a life saver
now i'll try work on the delete part based on ur work...thnx again ^^
delete is much more easier, because you dont need any parsing.
Just read line by line until found the album name. If so done, skip this and next 5-6 lines and write again to a copy of the file.

yeah......tatz what i'll do
thanx

euh.....sry to bother you again.....but if i enter an album name that doesnt exists it does not return me the error message but something else
Oh yea, forgot about this. Try after closing the file (immediatly after the loop):

1
2
if (album_info.artist.length() == 0)
   return;
but that only breaks out of the loop and goes back to the main menu
shouldnt it display an error message instead???
tatz ok...i kind of added the error message myself

if you could just explain to me wat this part of the program does would be great

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
if (!getline(in_file, album_lines[i])) 
            {
                cerr << "An error occured while reading from file.\n";
                return;
            }
        
            album_lines[i].erase(0, kPrefixAlbumLines[i].length());
        }
        
        album_info.artist = album_lines[0];
        stringstream converter;
        
        converter.str(album_lines[1]);
        if (!(converter >> album_info.category)) 
        {
            cerr << "Corruped data entry in category field!\n\n";
        }
        
        converter.str(album_lines[2]);
        converter.clear();
        if (!(converter >> album_info.stock)) 
        {
            cerr << "Corruped data entry in stock field!\n\n";
        }
    
        converter.str(album_lines[3]);
        converter.clear();
        if (!(converter >> album_info.price)) 
        {
            cerr << "Corruped data entry in price field!\n\n";
        }

Your info struct contains the information as numeric data types. But we are reading the file line by line into a string. A stringstream is possibility to make a string into an iostream (means it is handled same like your output and input cout/cin). Like this we can "convert" and extract the values (given as a string) into any data type we like to. Just like with cout and cin.

Thats why i named the stringstream "converter".
With the method str() (which is the only one different from cin/cout) i set the new buffer string, we read from. To make sure we can read without being stopped by any error flags i have to clear every time after settings the buffer. And now we can use the stringstream "converter" just like we are used to with files or with cin or cout.

You know, thats standard when converting from strings into numeric values or the other way around. In C we could only use things like atoi() but streams are more powerfull.

Maikel
hmmm....ok....got it
thnx a lot 4 ur help Maikel
i really appreciate it ^^
hi.....nid help again :-(

i need to delete a specific album from my file
for that i need to search for that particular album first
that sort of is identical to the code for the second part where i need to search for a particular album
once found i need to remove all the details for that album
how to delete a line in a text file???
from what i understood i need to rewrite the whole text file again leaving out the particular record that i want to erase

here is what i managed to write

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
char ans;
     system("CLS");

    ifstream in_file("database.txt");
    if (!in_file.is_open()) 
    {
        cerr << "Error: could not find database.txt" << endl;
        return;
    }

    item album_info;
    cout << "Enter the name of the album you want to delete : ";
    if (!getline(cin, album_info.name)) 
    {
        cerr << "Error while reading from keyboard.\n";
        cin.clear();
        return;
    }

    string line;
    while (getline(in_file, line)) 
    { 
        size_t pos = line.find(album_info.name);
        if (pos == string::npos) 
        {
            continue;
        }
        
  
        const string kPrefixAlbumLines[] = {"Album Artist : ","Category : ","Amount in Stock : ","Price : "};
    
        string album_lines[4];
        for (int i = 0; i < 4; i++) 
        {
            if (!getline(in_file, album_lines[i])) 
            {
                cerr << "An error occured while reading from file.\n";
                return;
            }
        
            album_lines[i].erase(0, kPrefixAlbumLines[i].length());
        }
        
        album_info.artist = album_lines[0];
        stringstream converter;
        
        converter.str(album_lines[1]);
        if (!(converter >> album_info.category)) 
        {
            cerr << "Corruped data entry in category field!\n\n";
        }
        
        converter.str(album_lines[2]);
        converter.clear();
        if (!(converter >> album_info.stock)) 
        {
            cerr << "Corruped data entry in stock field!\n\n";
        }
    
        converter.str(album_lines[3]);
        converter.clear();
        if (!(converter >> album_info.price)) 
        {
            cerr << "Corruped data entry in price field!\n\n";
        }
    
    }
      

    if (album_info.artist.length() == 0)
    {
            cout << "\n\nThe album doesnt exist or the name has been mispelled"<< endl;
            cin.get();
            system("CLS");
            return;
    }
    
 
    cout << endl << endl;
    cout << "Album Name : "      << album_info.name     << endl;
    cout << "Album Artist : "    << album_info.artist   << endl;
    cout << "Category : "        << album_info.category << endl;
    cout << "Amount in Stock : " << album_info.stock    << endl;
    cout << "Price : "           << album_info.price    << endl;
    cout << "\n\n";
    
    cout << "Are you sure you want to delete this album (y/n)???" << endl;
    cin >> ans;
    
    if (ans == 'n')
    {
    }
    
    if (ans == 'y')
    {
           ofstream out_file("nouveau.txt");
           
           while (getline(in_file, line))
           {
                 if((line != (album_info.name)) && (line != (album_info.artist)) && (line != (album_info.category)) && (line != (album_info.stock)) && (line != (album_info.price)))
                            out_file << line << endl;
           }
    }
    
    else
        cout << "Worng choice!!" << endl;
        
    in_file.close(); 
    out_file.close();
    
    remove("database.txt");
    rename("nouveau.txt","database.txt");
    
    return ans;


but it doesnt seem to work

anyone can help plz!!!
Welcome to www.manoloblahnikcvs.com, from here you will hunt for any designer shoes which you desire!all

style [URL="http://www.manoloblahnikcvs.com/"]Manolo Blahnik Boots sale [/URL]Ever since 2005, when we

became the best online dealer of authentic Giuseppe Zanotti , Gucci,

[URL="http://www.manoloblahnikcvs.com/"]Cheap Manolo Blahnik Boots[/URL],Cheap Ugg Boots , Yves Saint

Lauret , [URL="http://www.manoloblahnikcvs.com/"]Christian Louboutin [/URL], and were upgraded to be a

retailer for these brands,we have been devoted to provide customers with a large selection with finest

quality at lowest price.We strive to build long-term relationship with each and every one of our customers,

we can only accomplish our mission if you’re happy with the products you buy.So we’ve created a guarantee

that takes all the risk out of shopping!All goods shipped are insured, free and no customs taxes!1-2days to

pick up and 5-6days to your doors!you can also have a good view in our ed hardy clothing store.
Topic archived. No new replies allowed.