比较字符串与const char *总是false

时间:2013-01-19 21:19:06

标签: string char compare fstream getline

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

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

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

getline(tmpl, line);

然后我想比较一下这一行:例如:

if(line == "$something")

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

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

使用string.find()

问题已修复。当我尝试不同的东西时,我误用了它。但是,与==进行比较的问题仍然存在。

3 个答案:

答案 0 :(得分:0)

更改您的代码以使用它:

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

答案 1 :(得分:0)

尝试下面的代码..我认为它会起作用......

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

答案 2 :(得分:0)

好的,现在尝试以下代码......

#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;
}
相关问题