【问题标题】:compare string to const char* always false将字符串与 const char* 进行比较总是假的
【发布时间】:2013-01-03 08:21:17
【问题描述】:

我正在尝试将字符串与 const char* 进行比较。

std::string line;
std::fstream tmpl;

我使用 getline 用 fstream 文件中的一些输入填充字符串变量:

getline(tmpl, line);

然后我想将这条线与某些东西进行比较,例如:

if(line == "$something")

由于某种原因,它总是返回 false。 我已经尝试了很多不同的东西,但都没有成功(要么让它总是返回 false 要么总是 true)

为什么以及如何解决此问题?我错过了什么? getline 不是正确的方法吗?

问题已修复,使用 string.find()。当我尝试不同的事情时,我误用了它。然而,与== 比较的问题仍然悬而未决。

【问题讨论】:

  • 您是否尝试过打印类似:std::cout << "[" << line << "]" << std::endl; 的内容?它可能有助于调试。此外,$ 只是您示例中字符串的一部分,对吧?
  • 确保该行不包含空格或您缺少的任何其他字符。正如鲁本斯所说,最好的办法是在一些括号内输出您要比较的字符串。
  • 哇,没关系。使用std::cout << "[" << line << "]" << std::endl;的结果实际上是]$something
  • 似乎该问题已通过进一步尝试解决。输出符合预期[$something] 但仍不匹配"$something"

标签: string char compare fstream getline


【解决方案1】:

好的,现在试试下面的代码...

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  string sample ="hi";
  string datatoprocess ="";
  ifstream myfile ("example.txt");
if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      datatoprocess = datatoprocess + line;
    }
  unsigned found = datatoprocess.find(sample);
  if (found!=std::string::npos)
    std::cout << "Record Found";
    myfile.close();
  }
else cout << "Unable to open file"; 

  return 0;
}

【讨论】:

  • 是的,但我不太明白怎么做。我想在没有初始化的情况下使用 line 可能是一个错误。
  • 您要求将字符串与文件数据进行比较...所以我读取文件的所有内容并将其放入字符串中...然后从该字符串中检查字符串是否为compare 存在与否.... 如果存在则比较为 TRUE 否则为 FALSE... 明白...?
  • 哦,我现在发现了错误。我以错误的方式使用了 string.find。这就是为什么我没有那样解决它。然而,这仍然留下了关于使用== 进行比较本身的问题。
【解决方案2】:

更改您的代码以使用它:

if (strcmp(line,"$something")==0)

【讨论】:

  • c++ 中使用== 符号比较字符串是有效的,因为字符串的基本定义包括一个全局operator==,它实际上调用strcmp
  • 必须是 line.c_str() strcmp 不适用于 std::string。但是结果是一样的
【解决方案3】:

试试下面的代码..我认为它会工作......

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  string sample ="hi";
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
    if(line.compare(sample) == 0)
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

【讨论】:

  • 这开始让我感到更加沮丧。我尝试了您发布的代码,但 cout &lt;&lt; line &lt;&lt; endl; 行从未被执行...
猜你喜欢
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 2021-11-20
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多