若该语句不起作用,则该语句为真

If statement is not working even statement is true

本文关键字:语句 不起作用      更新时间:2023-10-16

我的文本文件包含

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

==测试比较地址valfile_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函数。

字符数组没有比较运算符。所以不是比较数组本身,而是比较数组的第一个元素的地址。