c++macosfile-ioconstants

Compiler problem in a (very) simple C++ program that gets numeric input from a file


#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

const int FILENAME_MAX=20;

int main() {

    ifstream input;
    char name[FILENAME_MAX + 1];
    int value;

    do {

        cout << "Enter the filename (maximum of " << (FILENAME_MAX+1) 
        << " characters: ";
        cin >> name;
        input.open(name);

    } while(input.fail() );

    while(input >> value) {
    int count=1;

    cout << "value #" << count << "\t" << value << endl;

    count++;
    }

return 0;
}

This is a very simple piece of code for reading some numbers from a file. Unfortunately I can't get it to compile. There is an error after/on the line "const int FILENAME_MAX=20;" The error says "expected unqualified-id before numeric constant."

Could someone please tell me what I am doing wrong?


I am compiling on Mac OS 10.5.8 with Xcode 3.0


Solution

  • FILENAME_MAX is a macro that is defined by the standard library*, and so it is already taken for use as an identifier. When you try to use it as an identifier, it's actually being replaced during preprocessing to some number. A number is not a valid identifier, so you get an error. (Which is why it's saying "I was expecting an identifier, not a numeric constant.")

    Rename it to something else. (Or use std::string, though it seems you aren't quite there yet.)

    *It is defined by <cstdio>. While you don't include it directly, other standard library headers are free to include any other standard headers as they see fit.