Search full string (not part of it) line by line

Hi I'm very new to coding and trying to write a simple code which can search from a file (mylist.txt) which basically contains list of numbers like below:

1234567
76543
1928
56677
321000

This is my code

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std; 

int main()
{

ifstream fin("mylist.txt");
string s, search;
bool permitted = false;

cout << "key in id" << endl;
cin >> search;


while (getline(fin,s)) {
    if (s.find(search) != string::npos) {
        permitted = true;
        break;
    }
}
if (permitted) {
  cout << "found" << endl;}

else {
  cout << "not found" << endl;}

  system("PAUSE");
}


My problem is that when searching using only part of the string,eg 321 or 1, it will return as true as well. my requirement is that only a full line by line string search will return as true and not only part of it. How do I improve this?
Last edited on
If you mean to check if the searched string is the same as the different lines in your file, you can try this:

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std; 

int main()
{

ifstream file("mylist.txt");
string s, search;
bool permitted = false;

cout << "key in id" << endl;
cin >> search;


while (getline(file, s, '\n'))
{
    if (s == search) //CHANGED HERE
    {
        permitted = true;
        break;
    }
}

if (permitted)
  cout << "found" << endl;
else
  cout << "not found" << endl;


  system("PAUSE");
  
  return 0;
}


if (s.find(search) != string::npos)
What you're doing here is, you are looking for the string search WITHIN the string s.

I believe you want to simply compare s and search to see if they are the same. you can do so like this:
if (s == search)

Hope this helps

Regards,

Hugo.
Last edited on
Yes this is exactly what i need. Thank you very much Hugo!

My pleasure! Glad to be of any help.
Topic archived. No new replies allowed.