【问题标题】:I am facing issues reading an input file line by line using c++我在使用 C++ 逐行读取输入文件时遇到问题
【发布时间】:2020-04-14 22:42:45
【问题描述】:

我已经编写了以下代码来逐行读取文本:

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

但是代码显示如下错误:

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

for the if statement.

如何克服这个错误?除此之外,如果您能告诉我如何读取格式为 .pdb 而不是 .txt 的文件,您将非常感激。如果 .pdb 在强制情况下可以在记事本中打开。

【问题讨论】:

标签: c++ string file-handling


【解决方案1】:

这些错误实际上告诉你到底出了什么问题。

在您的示例中,您将字符与字符串文字进行比较。您基本上是将line 的一个字母的值与作为指针的const char * 进行比较。

如果您想改为比较字符,则需要使用单引号表示法(即'H' 而不是"H")。

更好的解决方案是将您的条件更改为:

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

【讨论】:

  • 为什么不==? (否则评论太短)
  • @Evg 那也行。我想提供一个更“详细”的解决方案,因为 OP 似乎在混合数据类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-28
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多