4

And please don't say it's fscanf() ;P

I'm trying to replace this line:

if ( fscanf(fp, "P%c\n", &ch) != 1 )

If I understand correctly, it tries to read in a char and store it to &ch, only if it's between a 'P' and a '\n'. Is that right? And if it succeeds, it returns 1 (the number of characters it read)?

I'm trying to come up with a C++ version. Is there any easy way to do a formatted read like that? Or do I need to use fstream, operator>>, and nested if statements?

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
Andre
  • 291
  • 1
  • 4
  • 4
  • 2
    fscanf is a perfectly cromulent C++ function. What's your objection to using it? – Jim Lewis Jul 24 '10 at 22:16
  • Possible duplicate of http://stackoverflow.com/questions/2537500/what-is-the-modern-equivalent-c-style-for-the-older-c-like-fscanf-method – Sam Miller Jul 24 '10 at 22:22
  • If fscanf() is fine to use in C++, why does my compiler tell me it's unsafe? :-( – Andre Jul 24 '10 at 22:36
  • What compiler are you using? I'm not sure, but I think that there are some functions that the VS compiler consider unsafe but I think that the same warning would occur if you were compiling a pure C program. – Alceu Costa Jul 24 '10 at 22:40
  • I'm using Visual Studio 2010, so whichever compiler came with that. I need this to run on Mac and possibly linux systems as well, preferably building without warnings... – Andre Jul 24 '10 at 22:43
  • 3
    VC++ considers it unsafe because it relies on the existence of a `null` terminator. It prefers if you use (the non-standard) `fscanf_s`. To suppress the warning, you can place `#pragma warning(suppress:4996)` on the lines immediately before calling `fscanf`. Non-MSVC compilers won't understand this statement, but should ignore it. g++ does. – Gunslinger47 Jul 25 '10 at 01:42

2 Answers2

4

Safe C++ alternative with type checks is std::stringstream.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
  • Yeah, I've looked at this a bit, but I can't seem to find a way to format the input like fscanf did ("P%c\n"). Am I stuck doing it the tedious way? – Andre Jul 24 '10 at 22:46
  • 1
    I think that you can use stringstream to read the whole line as a string. Then you can get you char at the proper position in you string. – Alceu Costa Jul 24 '10 at 22:48
1

In Visual Studio, the safe, but non-portable, equivalent function is fscanf_s.

In general, for portability, you would use one of the stream classes, which, as you note, can be a pain to format correctly.

jwismar
  • 12,164
  • 3
  • 32
  • 44