Receiving an "Error: expected an identifier" on C++ for "=="

Receiving an "Error: expected an identifier" on C++ for "=="

我在“if (f_in); std::ifstream == int NULL;”上收到错误代码,其中“==”作为错误加下划线表示 "Error: expected as an identifier"。我不确定该怎么做,我被卡住了:/。这是代码:

#include <iostream>     // For cin/cout
#include <fstream>      // For file stream objects (ifstream)
#include <string>       // For the string data object

using namespace std;

int main()
{

   ifstream f_in;   // Creat an object for an 'input' file stream
   string       data;   // An object to hold our data read in form the file


  )

f_in.open("InputData.txt"); 

if (f_in); std::ifstream == int NULL); {
    fprintf(stderr, "Can't open input file in.list!\n");
    exit(1);
}


f_in >> data;
cout << "First data item from file is: ' " << data << endl;

f_in >> data;
cout << "Second data item from file is: ' " << data << endl;

getline(f_in, data);
cout << "Line from file is: '" << data << endl;

getline(f_in, data);
cout << "Next line from file is: '" << data << endl;

// We are finished with the file. We need to close it.
f_in.close();

cout << "Finished!\n";

return 0;
}
if (f_in); std::ifstream == int NULL);

您可以将其重写为:

if (f_in)
    ;
std::ifstream == int NULL);

而且你可以看到这没有任何意义。

也许你的意思是:

if (!f_in) {
    fprintf(stderr, "Can't open input file in.list!\n");
    exit(1);
}

或者

if (f_in == NULL) {
    fprintf(stderr, "Can't open input file in.list!\n");
    exit(1);
}

您可以将语句重写为

if (f_in); // actually do nothing if the condition is true
std::ifstream == int NULL); { // starts like a variable declaration

这就是编译器需要标识符的原因。 接下来,您有另一个未决错误,其中包含 int NULL(类型值)。 你可能想写这样的东西:

if (f_in.is_open())

查看 ifstream 参考:http://www.cplusplus.com/reference/fstream/ifstream/