我想我在比较中面临逻辑错误

I think I'm facing a logical error in comparison

本文关键字:错误 比较      更新时间:2023-10-16

我正在做字符串比较,但有一个问题。 我有一个写入12345的文件,然后我制作了另一个源文件并执行输入(输入12345)。 然后我通过bool true false逻辑进行比较,但问题是bool永远不会成真,我认为比较中存在逻辑错误,但我没有得到其中的错误。

#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;
}

您正在比较指针,而不是值。看看 strcmp

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

并删除break,因为它将在您执行输出之前退出您的while循环。

if(str==CNIC)不会做你认为它做的事情。它比较内存中存储两个字符串的位置,这些位置永远不会相同。

您的问题被标记为C++因此您无论如何都不想使用char指针和数组来做事。我可能会建议将strCNIC更改为std::string.然后使用 std::getline 读取字符串。如果您愿意,您甚至可以在CNIC上进行长度健全性检查,而不是获得5个单个字符。

此外,while 循环中的eof签入不是检查流有效性的方法。将str更改为std::string后,只需使用while(std::getline(file1, str))即可。