Reputation: 1
New to C/C++/C#. Is there any way to use __LINE__
to return the current line number of the input file read through stdio.h (e.g., getchar())? If not, is there another better way to do it?
Upvotes: 0
Views: 256
Reputation: 17573
__LINE__
is a special C/C++ Preprocessor define that is translated to the source code file line number of the current line in the source code file that is being processed. It has nothing to do with any kind of input or output from the actual C/C++ program.
__LINE__
along with another special C/C++ Preprocessor define of __FILE__
is often used when generating logs to provide the source code file name (which is what __FILE__
is defined as) and the specific line number (which is what __LINE__
is defined as).
So there may be a log function, whose interface looks like log (char *pszMessage, char *pszFile, int iLineNo)
and you could use it something like log ("My Log message", __FILE__, __LINE__);
These are special built-in defines whose values are changed by the Preprocessor as it opens and processes a source file.
As mentioned by Basile Starynkevitch, if you want to count lines you will need to use one of the C/C++ input functions/objects to read lines and count them as you read them.
Upvotes: 1
Reputation: 1
No, __LINE__
has nothing to do with the standard input. It is just macro-expanded by the compiler (to the line number inside the source code file).
If you need to count the lines of the standard input, read it line by line with getline(3) or std::getline and friends in C++ ...
Don't use fgets
or the old and dead gets
Upvotes: 8