0

I have written the following code to read the text line by line :

#include <bits/stdc++.h>
using namespace std;

int main()
{
    ifstream fin;           //  input and
    ofstream fout;          //  output
    string line;            //  syntax.

char filename[512];                                     
cout << "Enter the absolute path to the file:";         
cin >> filename;                                        
fin.open(filename);                                     
if ( fin.fail() ) {                                     
cerr << "Could not open file " << filename << endl;     
exit(1);                                                
}                                                       

while (std::getline(fin, line)){
    if((line[0] == "H" && line[1] == "E" && line[2] == "T" && line[3] == "A" && line[4] == "T" && line[5] == "M") ||
       (line[0] == "A" && line[1] == "T" && line[2] == "O" && line[3] == "M"))
       cout << "hello" << endl;
}
}

But the code displays the following error :

warning: comparison with string literal results in unspecified behaviour [-Waddress]|
error: ISO C++ forbids comparison between pointer and integer [-fpermissive]|

for the if statement.

How do I get past this error? In addition to this, it would be very kind of you if you could tell me how can I read files with format .pdb and not .txt. If .pdb is openable in notepad if forced to.

  • [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) / [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Evg Dec 23 '19 at 16:52
  • Even when I used #include and #include, same problem persists. – Tapasvi Bhatt Dec 23 '19 at 17:13
  • 1
    My comment was not an answer to your question, but a general recommendation. – Evg Dec 23 '19 at 17:14
  • Oh. I am new here that's why I didn't know. Thanks ! – Tapasvi Bhatt Dec 23 '19 at 17:20
  • 2
    Next time you post a bug with an error message, please include a comment in the code, so we know where the error is. Something like `// – TonyK Dec 23 '19 at 17:25

1 Answers1

1

These errors actually tell you exactly what's wrong.

In your example you are comparing chars to string literals. You are basically comparing the value of one letter of line to a const char * which is a pointer.

If you would like to compare characters instead, you would need to use the single quote notation (i.e 'H' instead of "H").

A better solution would be to change your condition to this :

if (!line.compare("HETATM") || !line.compare("ATOM"))
{
    std::cout << "hello" << std::endl;
}
Storm
  • 677
  • 6
  • 11