#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 compili开发者_运维百科ng on Mac OS 10.5.8 with Xcode 3.0
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.
Why do you make FILENAME_MAX
all upper-case? All upper-case is usually used for macros, and when you hit one (as you do) the preprocessor will mindlessly trample over your code doing the dumbest replacements.
Reserve such identifiers for macros, don't use macros unless you really must (which is rarely ever the case in C++), and this won't happen.
FILENAME_MAX
is probably a #define
somewhere. Try #undef FILENAME_MAX
.
FILENAME_MAX is already defined in stdio.h. Change your const name.
I am on Ubuntu Linux and I could compile it. I changed the FILENAME_MAX to F_M and it worked.
精彩评论