I am having trouble with multiple chars and scanf_s() [duplicate]

佐手、 提交于 2019-12-02 04:48:28

You have not provided a length indicator. From MSDN:

Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable. For example, if you are reading a string, the buffer size for that string is passed as follows: char s[10]; scanf_s("%9s", s, _countof(s)); // buffer size is 10, width specification is 9

Here is a link to that page.

If you really want to use (less portable) scanf_s, from the C11 standard (n1570), Annex K 3.5.3.2 p.4:

The fscanf_s function is equivalent to fscanf except that the c, s, and [ conversion specifiers apply to a pair of arguments (unless assignment suppression is indicated by a *). The first of these arguments is the same as for fscanf. That argument is immediately followed in the argument list by the second argument, which has type rsize_t and gives the number of elements in the array pointed to by the first argument of the pair.

You need to give the lengths of your char * arguments:

scanf_s("%f %c %c", &inTemp, &inUnit, 1, &outUnit, 1);

Alternatively, just use scanf:

scanf("%f %c %c", &inTemp, &inUnit, &outUnit);

And, as always, check the return values.

In general, as scanf is somtimes useful for little quick-and-dirty programmes, it’s of less use for productive software, because handling errors is hard. Use fgets and sscanf/strtod/strtol/… instead.

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