若该语句不起作用,则该语句为真
If statement is not working even statement is true
我的文本文件包含
Wew213
Wew214
Wew215
我在程序中的输入是
Wew213
但它显示我输出
"Not Matched"
实际上,我要做的是输入,如果输入与文本文件中的数字匹配,它应该通过if语句运行输出,否则为else语句
这是我的程序
char file_data[10];
std::ifstream file_read ("D:\myfile.txt");
cout<<"Enter the number to search"<<endl;
char val[10];
cin>>val;
while(!file_read.eof())
{
file_read>>file_data;
cout<<file_data<<endl;
}
if (val == file_data)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
}
您正在比较指针值,这与不同
您需要使用strcmp
来比较c字符串。或使用std::string
if (strcmp(val, file_data) == 0)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
或
if (std::string(val) == std::string(file_data))
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
==
测试比较地址val
和file_data
。代替==
,使用函数strcmp()
来比较字符数组的内容。
给定的代码,
char file_data[10];
std::ifstream file_read ("D:\myfile.txt");
cout<<"Enter the number to search"<<endl;
char val[10];
cin>>val;
while(!file_read.eof())
{
file_read>>file_data;
cout<<file_data<<endl;
}
if (val == file_data)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
}
通过AStyle:运行后看起来是这样的
char file_data[10];
std::ifstream file_read ("D:\myfile.txt");
cout<<"Enter the number to search"<<endl;
char val[10];
cin>>val;
while(!file_read.eof())
{
file_read>>file_data;
cout<<file_data<<endl;
}
if (val == file_data)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
}
因此,由于检查是在循环之后完成的,因此只检查循环读取的最后一个项,即使字符串比较本身正确,程序也不会工作。
这种比较不起作用,因为正如其他人(匆匆忙忙)已经指出的那样,你在比较指针,而不是字符串。
要比较字符串,请使用std::string
而不是字符数组。
轻微修正:代替
while(!file_read.eof())
写入
while(!file_read.fail())
或者只是
while(file_read)
它为您调用CCD_ 9(否定结果)。
但这样做,还必须检查输入操作的成功/失败。
通常的习惯用法是直接这样做:
while( file_read>>file_data )
==运算符将简单地比较地址。您将需要使用strcmp函数。
字符数组没有比较运算符。所以不是比较数组本身,而是比较数组的第一个元素的地址。
相关文章:
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- C++ 中断语句不起作用
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 切换语句不起作用 c++ 和 D:\c++ dev-c\Makefile.win 目标"abc.o"的配方失败
- C++ SQLite3 准备的删除语句不起作用
- std::cin 语句不起作用 C++
- 为什么我的 if 语句不起作用
- if 语句不起作用并被跳到 else 部分
- 如果宏中的语句不起作用
- 为什么嵌套如果语句不起作用
- SQLLITE UPDATE语句不起作用
- 选择在 Sqlite 数据库中有效,但插入和更新语句不起作用
- 我的 1 行 if-else 语句不起作用
- 如果统计语句不起作用
- 如果语句不起作用 VS2010
- 如果-否则语句不起作用
- 若该语句不起作用,则该语句为真
- 若语句不起作用,我希望它能起作用
- 为什么这个"if"语句不起作用?
- 如果带有字符串的语句不起作用