我的代码工作不正常,我认为它的逻辑错误,但我没有得到它

时间:2015-01-26 13:24:57

标签: c++ file-handling dev-c++

它不能正常工作,因为我希望它工作..根据我的想法,下面给出的代码总是正确的我不知道为什么但if-condition总是为真且数字匹配。变量命名因为CNIC在全球范围内宣布如此(char CNIC [15])..

  private:
     char ch;
     char str[256];

     std::fstream file1;
  public:
    void verify()
    {
          cout<<"Enter your CNIC number for verifivation : ";
          for(int i=0;i<15;i++)                    
          {
                   CNIC[i] = getche();
          }

          file1.open("D:\\UOL\\OoP\\Nadra database.txt",ios::in);
          check = false;
          while(!file1.eof())
          {         
                file1.getline(str, 255);     
            if(check = strcmp(str, CNIC) == 0);
                 check=true;
          }
          file1.close();
          if(check)
          {
                 cout<<endl<<"CNIC number matched"<<endl;
                              }
          else
          {
                 cout<<endl<<"CNIC number did'nt match " ;
          }
    }
};

1 个答案:

答案 0 :(得分:0)

您的代码包含几个错误。

if语句由;终止,因此check将始终设置为true

// the ';' terminates the if statement
if(check = strcmp(str, CNIC) == 0);
  // check will always be set to true
  check=true;

您需要删除分号,将代码更改为:

if(strcmp(str, CNIC) == 0) {
  check=true;
  // my guess would be that you really like to break the loop here
  break;
}

我还必须在for循环后向CNIC添加一个终止空字符,你需要为变量{16}中的16个字符腾出空间,以便为空字符腾出空间:

char CNIC[16];