【问题标题】:If statement is not working even statement is true如果语句不起作用,即使语句为真
【发布时间】:2013-12-08 21:04:48
【问题描述】:

我的文本文件包含

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

【问题讨论】:

  • while(!eof(file))always wrong
  • @H2CO3 我读了两遍,但没明白他的意思,这是不是while(!eof(file)) 比它需要的多读了一次文件

标签: c++


【解决方案1】:

你在比较指针值,这是不同的

您需要使用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;
}

【讨论】:

    【解决方案2】:

    == 测试比较地址valfile_data。使用函数strcmp()来比较字符数组的内容,而不是==

    【讨论】:

      【解决方案3】:

      给定的代码,

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

      所以,由于检查是在循环之后 完成的,因此只检查循环读取的 last 项,即使字符串比较本身正确,您的程序也会不工作。

      比较不起作用,因为正如其他人(冲进来)已经指出的那样,您是在比较指针,而不是字符串。

      要比较字符串,请使用 std::string 而不是字符数组。


      小修正:代替

      while(!file_read.eof())
      

      while(!file_read.fail())
      

      或者只是

      while(file_read)
      

      为您调用fail(否定结果)。

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

      常见的做法是直接这样做:

      while( file_read>>file_data )
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            猜你喜欢
            • 2020-03-16
            • 2012-12-26
            • 2013-06-20
            • 2013-09-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多