首页 > 解决方案 > 使用一个scanf()(或fscanf())更好还是没关系?

问题描述

我听说scanf()“花费很多”,但现在我找不到任何相关信息。因此,我是使用一个fscanf("%f", &num)值还是在一行中查找多个值 ( fscanf("%f %f %f %f", &num, &num1, &num2, &num3)) 是否重要?附加问题:您能否推荐一些有关此类信息的资源,以了解程序的功能成本是多少?

我知道标题中有 scanf(),但 fscanf()、sscanf() 和 scanf() 可以在手册的同一页上找到,因此我相信标题不会误导。

标签: cinputscanf

解决方案


They should perform exactly the same.

fscanf reads from an open file stream; "File Scan Formated".

scanf does exactly the same thing, but it only reads from stdin. scanf(format, ...) is just fscanf(stdin, format, ...).

Additional question: could you recommend some sources for that type of information about how much a function can cost to the program?

This will depend on your implementation. The reality is functions like scanf are unlikely to be a performance issue. They have been optimized for decades. Performance problems come from things like loops and bad algorithms. Look into subjects such as Big-O Notation for the basics, and tools such as benchmarking and profilers to test running programs.

What you should concern yourself with is the many problems with scanf and fscanf. The big problem being that they tie together reading input with parsing it. Consider using fgets and sscanf (S for String) instead to separate the two: read a line, parse a line.


推荐阅读