compare input string to string vector

Hello,
I wrote a program that reads a list from a file and stores it in a string type vector. Now, I want the user to input a word so that the program can search the vector to see if that word already exists. I have used every possible way of reading input from the console and storing it in order to compare with the vector but it never results in a match. When I print the input string and the vector string they are exactly the same thing (or at least print to the console as if they were). I've tried using getline; using cin direct to a string var; using cin to a char array and then casting to string using string str(arr); I even added a newline at the end just in case and STILL I cannot get a match.

Any help would be greatly appreciated! Thanks in advance.

vector <string> currentSet; //read a list in from a file and has 9 items in it
cin.ignore();
string line;
getline(cin, line);
if(line == vector[0]){//if printed to console line is HEAT and vector[0] is HEAT
cout<<"match"<<endl;
}

You don't supply enough code or information to determine where the problem may be. Perhaps the following will be of some help.

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



int main()
{
    std::vector<std::string> currentSet =
    {
        "HEAT",
        "COLD",
        "WARMTH",
        "COOLNESS",
    };

    std::string input;
    std::getline(std::cin, input);

    auto it = std::find(currentSet.begin(), currentSet.end(), input);

    if (it == currentSet.end())
        std::cout << '"' << input << "\" was not found.\n";
    else
        std::cout << '"' << input << "\" was at index " << it - currentSet.begin() << " in currentSet\n";
}


http://ideone.com/zxP14u
you should call the vector you declared, not the class itself:
1
2
3
4
5
6
7
8
9
vector <string> currentSet; //read a list in from a file and has 9 items in it
cin.ignore();
string line;
getline(cin, line);

     if(line == currentSet[0]){//if printed to console line is HEAT and vector[0] is HEAT
      cout<<"match"<<endl;
}
}
Last edited on
cire, thanks for the reply. I tried what you suggested and its weird because say I read in a list from a file into my currentSet that looks like this:

guava
carambola
grapefruit
banana

The program only finds the last item of whatever the list is. I am thinking it has something to do with a return character or something.

gudeh, thanks for the reply. I apologize; in my actual code I do use currentSet[0] in my comparison statement. It does not work however, even though printing out each of them to the screen individually produces the same thing.
Topic archived. No new replies allowed.