开发者

C++ equivalent of fscanf()?

开发者 https://www.devze.com 2023-01-09 05:38 出处:网络
And please don\'t say it\'s 开发者_StackOverflowfscanf() ;P I\'m trying to replace this line: if ( fscanf(fp, \"P%c\\n\", &ch) != 1 )

And please don't say it's 开发者_StackOverflowfscanf() ;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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消