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

C++ 若语句不起作用,则该语句为真,c++,C++,我的文本文件包含 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

我的文本文件包含

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;
    }
}
char文件_数据[10];
std::ifstream文件_read(“D:\\myfile.txt”);
coutfile_数据;

cout您正在比较不同的指针值

您需要使用来比较c字符串。或使用

if(strcmp(val,文件数据)==0)
{

cout测试比较地址
val
文件数据
。要比较字符数组的内容,请使用函数
strcmp()代替
=

字符数组没有comparison运算符。因此,您不需要比较数组本身,而是比较数组的第一个元素的地址。

给定的代码

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

或者只是

while(file_read)
为您调用
fail
(否定结果)

但这样做还必须检查输入操作的成功/失败

通常的习惯用法是直接这样做:

while( file_read>>file_data )

==运算符只需比较地址。您需要使用strcmp函数。

而(!eof(file))
是。@H2CO3我读了两遍,但没有领会他的意思,这是
而(!eof(file))
比需要多读一次文件吗
    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;
    }
}
while(!file_read.eof())
while(!file_read.fail())
while(file_read)
while( file_read>>file_data )