我想我在比较中面临逻辑错误
I think I'm facing a logical error in comparison
我正在做字符串比较,但有一个问题。 我有一个写入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
指针和数组来做事。我可能会建议将str
和CNIC
更改为std::string
.然后使用 std::getline
读取字符串。如果您愿意,您甚至可以在CNIC上进行长度健全性检查,而不是获得5个单个字符。
此外,while 循环中的eof
签入不是检查流有效性的方法。将str
更改为std::string
后,只需使用while(std::getline(file1, str))
即可。
相关文章:
- C++分数混合比较运算符错误
- 在C++中比较来自向量的字符串时出现分段错误
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- 黑客兰克中的错误比较三元组代码
- Qt 错误 iso c++ 禁止指针和整数之间的比较 -permissive
- 为什么Visual Studio没有对逻辑比较错误进行热身?
- qsort 比较函子的分段错误
- std::映射服装比较函数和函数/lambda错误
- 错误:ISO C++禁止在指针和整数 [-fallowive] 之间进行比较
- 错误:运算符 [] 不匹配。在比较列表中的 int 和 int 时<int>,
- 将子字符串与字符串数组进行比较的 IF 条件会在C++中产生错误
- 在 constexpr-if 条件下比较 constexpr 函数参数会导致错误
- 为什么使用 and 运算符比较 if 语句中的 2 个对象会抛出错误,而使用 2 if 语句则不会
- 比较枚举的值会给出编译器错误
- 如何修复C++中的"指针和整数之间的比较"错误?
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- boost :: fibonacci_heap:带有比较器重新定义圆形定义错误的嵌套定义
- C++ priority_queue使用带有 lambda 比较器错误的映射
- 分词错误-比较不同的单词在c++输入中出现的次数