algorithm problem

I made a program that searches through a vector of strings and it tells me if it found it or not.

the problem is if i try to search for one thats two words it only reads the first word I input. any ideas?

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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector<string> Inventory(9);
    Inventory.push_back("Motherboard");
    Inventory.push_back("CPU");
    Inventory.push_back("Hard Drive");
    Inventory.push_back("Power Supply");
    Inventory.push_back("DVD Drive");
    Inventory.push_back("RAM");
    Inventory.push_back("Video Card");
    Inventory.push_back("Sound Card");
    Inventory.push_back("Keyboard");
    Inventory.push_back("Mouse");

    string Search;
    string Answer;

    cout << "What item do you want to search for?" << endl;
    cin >> Search;

    vector<string>::const_iterator result = find(Inventory.begin(), Inventory.end(), Search);

    if(result == Inventory.end())
    {
        Answer = "Does not exist";
    }

    if(result != Inventory.end())
    {
        Answer = "Found!";
    }

    cout << Search << " " << Answer << endl;

    return 0;
}//main
instead of using
 
cin >> Search;


use

 
getline(cin, Search);


That should do it.
i think you should use loop while(1) from line 24 to 41
after put sequentially the key you want to search
good luck
also you could make a loop to see if the user wants to keep running the program. Simply just put a while loop...
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
string runAgain = "maybe";
while (runAgain != "yes" && runAgain != "Yes")
{

   // your coding
   while(runAgain != "yes" && runAgain != "Yes" && runAgain != "no" && runAgain != "No")
   { 
         cout << "Would you like to search for something else? ";
         cin >> runAgain;
   }
   if( runAgain == "yes" || runAgain == "Yes" )
   {
        // this section of code deletes and clears the vector
        // if you were to not clear the inventory then you would just multiple copies of each one, which you don't want
        for(unsigned i = 0; i < Inventory.size(); ++i)
       {
		delete Inventory[i];
	}
        Inventory.clear();
   }
   if( runAgain == "no" || runAgain == "No" )
   {
         break;
   }
}


this way if you want to keep trying to search for something the person can continue searching for it, if they want it, and it would be more of the user closing out of the program instead of the program just terminating and then they would have to recompile it in order to run it.
Last edited on
oh yeah i forgot about getline. i guess its been awhile. yeah i could probably thrown in a loop too.
Topic archived. No new replies allowed.