我认为我在比较中遇到了逻辑错误

时间:2015-01-15 16:18:33

标签: c++

我正在进行字符串比较,但是存在问题。我有一个文件,其中写有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;
}

2 个答案:

答案 0 :(得分:4)

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

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

并删除break,因为它会在您输出之前退出while循环。

答案 1 :(得分:0)

if(str==CNIC)并不能按照您的想法行事。它比较了存储两个字符串的内存位置,这些位置永远不会相同。

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

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