0

My code is all about finding that a particular name exists in names.txt or not

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ifstream file("names.txt");
    string names[6];
    string test;
    cin>>test;
    for(int i=0;i<6;i++)
    {
        getline(file, names[i]);
    }
    for(int i=0;i<6;i++)
    {
        if(names[i]==test)
        {
            cout<<"found";
            return 0;
        }

    }
    cout<<"not found";
    return 0;
}

here, in my code names.txt contains 6 names as:

john walker
rick jo
steaven fedrer
anil kumar
raju rastogi
priyanka raj

but when i enter a name present in name.txt then also it says "not found"(i am entering full name). Why? Where i am going wrong?

3 Answers3

1

C++ std::cin reads until the next whitespace, so only the firstname will be read in your code. You can solve this problem by using std::getline(std::cin, test).

Arno Deceuninck
  • 320
  • 3
  • 10
0

You shouldn't use cin with strings, try using getline(cin, test);

incbeatz
  • 101
  • 2
  • 10
0

I have edit your source code, it works now.

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

int main(int argc, char*argv[])
{
    std::ifstream file("names.txt");
    
    std::string names[6];
    std::string test;
    
    std::getline(std::cin, test);
    
    for (int i = 0; i < 6; i++)
    {
        std::getline(file, names[i]);
    }

    for (int i = 0; i < 6; i++)
    {
        if (!names[i].compare(test))
        {
            std::cout << "found";
            return 0;
        }

    }
    
    std::cout << "not found";

    return 0;
}
Timberwolf
  • 81
  • 7