0

I'm doing a string comparison but there is a problem. I have a file in which 12345 is written and then I have made another source file and performed input (input is 12345). Then I'm comparing it through bool true false logic but the issue is that the bool never gets true and I think that there is a logical error in the comparison but I didn't get what's wrong in it.

#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>

using namespace std;

int
main()
{
  char str[256];
  char CNIC[5];
  std::fstream file1;
  for(int i = 0; i < 5; i++)
    {
      CNIC[i] = getche();  // editor's comment: probably std::getchar()
    }
  file1.open("D:\\UOL\\OoP\\Nadra database.txt", ios::in);
  bool check = false;
  while(!file1.eof())
    {
      file1.getline(str, 255);

      if(str == CNIC)
        {
          check = true;
          break;
        }
      if(check)
        {
          cout << endl << "CNIC number matched" << endl;
        }
      else
        {
          cout << endl << "CNIC number didn't match" << endl;
        }
    }
  file1.close();
  system("pause");
  return 0;
}
5gon12eder
  • 21,864
  • 5
  • 40
  • 85

2 Answers2

4

you are comparing pointers, not values. have a look at strcmp

check = strcmp(str, CNIC) == 0;

and remove the break as it will exit your while loop, before you do the output.

esskar
  • 10,000
  • 3
  • 31
  • 55
0

if(str==CNIC) doesn't do what you think it does. It's comparing the location in memory where the two strings are stored, and these locations will never be the same.

Your question is tagged C++ so you don't want to be doing things with char pointers and arrays anyway. I would probably suggest changing str and CNIC to std::string. Then use std::getline to read the string. You can even do length sanity checking on the CNIC if you like, rather than getting 5 single characters.

Also, the eof check in your while loop is not the way to check for stream validity. After making the change of str to std::string just use while(std::getline(file1, str)) instead.

Mark B
  • 91,641
  • 10
  • 102
  • 179