C99 - vscanf for dummies? [closed]

拥有回忆 提交于 2019-12-13 20:34:11

问题


I am sorry to bother S.O. with such a general request for information.

I can find plenty of very terminology-heavy definitions of vscanf - but I can't find much in the way of concrete examples which will show what is being returned from the function, other than this quite nice one on the IBM infocenter site:

http://pic.dhe.ibm.com/infocenter/iseries/v7r1m0/index.jsp?topic=%2Frtref%2Fvscanf.htm

However this example is only for a one-line string input, whereas I am trying to do the same thing, but reading from a .txt file with multiple lines.

Do I have to use fgets() to read a line at a time and then use vscanf? Do I have to utilise it inside a function, the way that the IBM infocenter example does, by putting it inside a function vread()?

I am a first-year CS student, but this is not a question for an assignment, I am just trying to do some extra work and expand my knowledge, and we haven't got to vread/vscanf yet.

Should I just stick to using sscanf? My apologies if this is as stupid as that.

P.S. I love learning C. Most fun I have had as a student in my 31 years on this planet, apart from when I did a Shakespeare workshop with some people from the RSC once.


回答1:


vscanf is like scanf, not sscanf or fscanf. It differs from scanf in that scanf takes a variable number of arguments, whereas vscanf takes a va_list argument that acts as a pointer to a variable argument list. The use of vscanf is rare; it's mostly there for completeness (uses of vprintf are more common). A possible example of a use for vscanf is if you had a large number of scanf calls with different arguments, and on each occasion it takes some error action -- the same error action -- if scanf can't read all its arguments. Then you could write a scanf_and_check_for_error function that takes variable arguments just like scanf does, with the addition of a count argument that is the expected return value of scanf, passes the argument list to vscanf, checks its return value and takes the error action if the return value is wrong. e.g.,

void scanf_and_check(int count, char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    int rc = vscanf(fmt, ap);
    if (rc != count)
    {
        ErrorMessageBox("Bad input. This program employs a radical form of the fail-fast principle ... exiting!");
        exit(1);
    }
    va_end(ap);
}



回答2:


Without being too unhelpful, I suspect you may be trying the wrong tool for the job. vscanf is intended to be used when developing "front-ends" to the scanf family, and is a very "low-level" tool.

You probably want to use fscanf. In case you really want to use the vscanf logic (with all its va_list ugliness), take a look at vfscanf (linked in your example)



来源:https://stackoverflow.com/questions/17017331/c99-vscanf-for-dummies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!