C언어 > scanf(), fscanf()

TODAY580 TOTAL4,686,655
사이트 이용안내
Login▼/회원가입
최신글보기 질문게시판 기술자료 동영상강좌

아두이노 센서 ATMEGA128 PWM LED 초음파 AVR 블루투스 LCD UART 모터 적외선


BASIC4MCU | C언어 | C언어 | scanf(), fscanf()

페이지 정보

작성자 키트 작성일2017-09-12 12:59 조회2,006회 댓글0건

본문

13.5. scanf()fscanf()

 

Read formatted string, character, or numeric data from the console or from a file.

Prototypes

#include <stdio.h>int scanf(const char *format, ...);int fscanf(FILE *stream, const char *format, ...);

Description

The scanf() family of functions reads data from the console or from a <nobr>FILE</nobr> stream, parses it, and stores the results away in variables you provide in the argument list.

The format string is very similar to that in printf() in that you can tell it to read a "%d", for instance for an <nobr>int</nobr>. But it also has additional capabilities, most notably that it can eat up other characters in the input that you specify in the format string.

But let's start simple, and look at the most basic usage first before plunging into the depths of the function. We'll start by reading an <nobr>int</nobr> from the keyboard:

int a;scanf("%d", &a);

scanf() obviously needs a pointer to the variable if it is going to change the variable itself, so we use the address-of operator to get the pointer.

In this case, scanf() walks down the format string, finds a "%d", and then knows it needs to read an integer and store it in the next variable in the argument list, a.

Here are some of the other percent-codes you can put in the format string:

%d

Reads an integer to be stored in an <nobr>int</nobr>. This integer can be signed.

%f (%e%E, and %g are equivalent)

Reads a floating point number, to be stored in a <nobr>float</nobr>.

%s

Reads a string. This will stop on the first whitespace character reached, or at the specified field width (e.g. "%10s"), whichever comes first.

And here are some more codes, except these don't tend to be used as often. You, of course, may use them as often as you wish!

%u

Reads an unsigned integer to be stored in an <nobr>unsigned int</nobr>.

%x (%X is equivalent)

Reads an unsigned hexidecimal integer to be stored in an <nobr>unsigned int</nobr>.

%o

Reads an unsigned octal integer to be stored in an <nobr>unsigned int</nobr>.

%i

Like %d, except you can preface the input with "0x" if it's a hex number, or "0" if it's an octal number.

%c

Reads in a character to be stored in a <nobr>char</nobr>. If you specify a field width (e.g. "%12c", it will read that many characters, so make sure you have an array that large to hold them.

%p

Reads in a pointer to be stored in a <nobr>void*</nobr>. The format of this pointer should be the same as that which is outputted with printf() and the "%p" format specifier.

%n

Reads nothing, but will store the number of characters processed so far into the next <nobr>int</nobr> parameter in the argument list.

%%

Matches a literal percent sign. No conversion of parameters is done. This is simply how you get a standalone percent sign in your string without scanf() trying to do something with it.

%[

This is about the weirdest format specifier there is. It allows you to specify a set of characters to be stored away (likely in an array of <nobr>char</nobr>s). Conversion stops when a character that is not in the set is matched.

For example, %[0-9] means "match all numbers zero through nine." And %[AD-G34] means "match A, D through G, 3, or 4".

Now, to convolute matters, you can tell scanf() to match characters that are not in the set by putting a caret (^) directly after the %[ and following it with the set, like this: %[^A-C], which means "match all characters that are not A through C."

To match a close square bracket, make it the first character in the set, like this: %[]A-C] or %[^]A-C]. (I added the "A-C" just so it was clear that the "]" was first in the set.)

To match a hyphen, make it the last character in the set: %[A-C-].

So if we wanted to match all letters except "%", "^", "]", "B", "C", "D", "E", and "-", we could use this format string: %[^]%^B-E-].

So those are the basics! Phew! There's a lot of stuff to know, but, like I said, a few of these format specifiers are common, and the others are pretty rare.

Got it? Now we can go onto the next--no wait! There's more! Yes, still more to know about scanf(). Does it never end? Try to imagine how I feel writing about it!

So you know that "%d" stores into an <nobr>int</nobr>. But how do you store into a <nobr>long</nobr>, <nobr>short</nobr>, or <nobr>double</nobr>?

Well, like in printf(), you can add a modifier before the type specifier to tell scanf() that you have a longer or shorter type. The following is a table of the possible modifiers:

h

The value to be parsed is a <nobr>short int</nobr> or <nobr>short unsigned</nobr>. Example: %hd or %hu.

l

The value to be parsed is a <nobr>long int</nobr> or <nobr>long unsigned</nobr>, or <nobr>double</nobr> (for %fconversions.) Example: %ld%lu, or %lf.

L

The value to be parsed is a <nobr>long long</nobr> for integer types or <nobr>long double</nobr> for <nobr>float</nobr> types. Example: %Ld%Lu, or %Lf.

*

Tells scanf() do to the conversion specified, but not store it anywhere. It simply discards the data as it reads it. This is what you use if you want scanf() to eat some data but you don't want to store it anywhere; you don't give scanf() an argument for this conversion. Example: %*d.

Return Value

scanf() returns the number of items assigned into variables. Since assignment into variables stops when given invalid input for a certain format specifier, this can tell you if you've input all your data correctly.

Also, scanf() returns EOF on end-of-file.

Example

int a;long int b;unsigned int c;float d;double e;long double f;char s[100];scanf("%d", &a);  // store an intscanf(" %d", &a); // eat any whitespace, then store an intscanf("%s", s); // store a stringscanf("%Lf", &f); // store a long double// store an unsigned, read all whitespace, then store a long int:scanf("%u %ld", &c, &b);// store an int, read whitespace, read "blendo", read whitespace,// and store a float:scanf("%d blendo %f", &a, &d);// read all whitespace, then store all characters up to a newlinescanf(" %[^\n]", s);// store a float, read (and ignore) an int, then store a double:scanf("%f %*d %lf", &d, &e);// store 10 characters:scanf("%10c", s);

See Also

sscanf()vscanf()vsscanf()vfscanf()

 

http://beej.us/guide/bgc/output/html/multipage/scanf.html

 

 

 

 

 

 

 

 

Using (s)printf()

 

printf() and sprintf() work just like in C, with a few slight differences. printf() gives you a lot of control over the formatting of your values, which is what it was intended to do.

If you've ever wanted to make a nicely behaved, field-aligned report, round to an integer or specific decimal place, get octal or hexadecimal representations of your values, or just display your values in any other form imaginable, keep reading. printf() and sprintf() give you the utility to do that, and more.

 

printf() versus sprintf()

printf() and sprintf() look argumentally the same. That is, whatever arguments you pass to one, you can pass to the other without change. The difference is that printf() prints to a filehandle, and sprintf() returns the string printf() would have outputted.

To use printf() on a filehandle other than STDOUT, specify the filehandle you want to use just as you would with print, like so:

 

printf(HANDLE $format, @values);

The result will be printed to HANDLE.

sprintf doesn't take a filehandle, but instead returns the output into a string.

 

my $string = sprintf($format, @values);

The Format String

The format string in printf() is a number of tokens which describe how to print the variables you supply, and whatever else you want. Each variable format specifier starts with a %, is followed by zero or more of the optional modifiers, and ends with a conversion specifier.

A typical format string could look like this:

 "foo is %d"

Printed, it may look something like: 'foo is 12'. The %d is replaced by a variable specified after the format string argument. In this case, you would say:

 printf("foo is %d", $decimal);

so that %d is replaced with the value of $decimal. You can put as many specifiers in the format string as you like, with the same number of following arguments as there are specifiers. An example:

 printf("%d %s %f", $decimal, $string, $float);

Conversion Specifiers

You put these in your Format String. Each one, except %%, is replaced by the corresponding value in the printf argument list.

  • %% prints a single % (percent sign).
  • %c prints a single character with the given ASCII number (66 is printed as B, for example).
  • %s prints a given string
  • %d a signed integer in decimal
  • %u an unsigned (can't be negative) integer in decimal
  • %o an unsigned integer in octal
  • %x an unsigned integer in hexadecimal
  • %e a floating point number in scientific notation
  • %f a floating point number in fixed decimal notation
  • %g same as %e or %f, whichever printf thinks is best.
  • %X is the same as %x, except it uses upper-case letters
  • %E like %e, but with an upper-case 'E'
  • %G same as %E when scientific notation is used for the value.
  • %p a pointer; it outputs Perl's value address in hexadecimal.
  • %n an odd little bugger that *stores* (in the variable given for the position) the number of characters output so far.

Others that simply exist for backward compatibility:

  • %i synonym for %d
  • %D same as %ld (long decimal)
  • %U same as %lu (long unsigned decimal)
  • %O same as %lo (long octal)
  • %F same as %f

Format Specifiers

Each item below is optional (unless otherwise stated), and should be used in the order they appear here. If this is confusing, skip to the next section. It's intended as a reference, and copied from man 3 printf with some extra explanation and examples.

  • % - a percent sign. This is required, of course.
  • Zero or more of the following:
    • '#' (pound sign): Specifies that the value should be converted to an 'alternate form.' This has no effect on 'c''d''i''n''p''s', and 'u' conversions. For 'o' (octal) conversions, this prepends a '0' to the beginning. For 'x' and 'X' (hexadecimal), 0x or 0X is prepended to the value. For 'e''E''f''g'and 'G', the value is always printed with a trailing decimal point (.), even if no numbers follow it. For 'g'and 'G', trailing zeros are not removed from the result.
      printf("%x", 10);  # prints just 'a', versus:printf("%#x", 10);  # prints '0xa'
    • '0' (zero): To specify zero-padding on a digit. The converted value is padded on the left with the specified number of zeros minus the number of digits to be printed. This is described in more detail below.
      printf("%03d", 7);  # prints '007' ;)printf("%03d", 153);  # prints '153'
    • '-' (minus): Specifies a negative field width. This indicates the value should be left-adjusted on the boundary, versus the default right-adjusted. See below for more on how to specify field widths.
      printf("%5s", 'foo');  # prints '  foo'printf("%-5s", 'foo');  # prints 'foo  '
    • ' ' (a space): To specify that a blank should be left before a positive number.
      printf("% d", 7);  # prints ' 7'printf("% d", -7);  # prints '-7'
    • '+' (plus sign): This specifies that a sign always be placed before the value. '+' overrides ' ' (space) if both are used.
      printf(*quot;%+d", 7);  # prints '+7'
  • A decimal digit specifying the minimum field width. Using the '-' modifier (see above) will left-align the value, otherwise it is right-aligned. With the '0' modifier for numeric conversions, the value is right-padded with zeros to fill the field width.
    printf("%5s", 'foo');  # prints '  foo'printf("%-5s", 'foo');  # prints 'foo  '
  • A precision value in the form of a period ('.'), followed by an optional digit string. If the digit string is omitted, a precision of zero is used. This specifies the minimum number of digits to print for 'd''i''o''u''x', and 'X'conversions. For 'e''E', and 'F' conversions, it is the number of digits to appear after the decimal point. For 'g'and 'G' conversions, it specifies the maximum number of signifigant digits. For the 's' (string) conversion, it is the maximum number of characters of the string to print. Use the latter to make sure long strings don't exceed their field width.
    printf("%.3d", 7);  # prints '007'printf("%.2f", 3.66666); # prints '3.66'printf("%.3s", 'foobar'); # prints 'foo'
  • The character 'h' here will specify to treat the decimal value as a C type 'short' or 'unsigned short'.
    printf("%hd\n", 400000); # prints '6784'
  • The character 'l' (ell) can be used to treat the value as a C 'long' type.
  • The character 'V' will interpret an integer as Perl's standard integer type.
    printf("%Vd", 7);  # prints '7'
  • Finally, the required conversion specifier. Valid conversions are listed in the previous section.

Leading Zeros

Say you have a number, something like 642, and you want to output it as 00642 instead. The %0nC specifier syntax lets you do just that, where 'n' is the field width, and C is the conversion specifier you want to use. A field width is the minimum (in this case) number of characters the value should fill. Any less than that, and the remainder is filled by prepending zeros on your value until it fits perfectly.

 printf("%05d", 642);  # outputs '00642'

You should note that certain conversions, like %f, are a little trickier. Floating point numbers (with %f) are always outputted with 6 places after the decimal point, unless you specify a precision with the '.' modifier (see below for a discussion of the '.' precision modifier). In other words, printing a value of '2' as %f will actually output as 2.000000. This means you have to take into account, when specifying the field width, that there are already 7 characters tacked on. To get the value of 2 to print with one leading zero, you have to use a field width of 9 (7 for the '.' and 6 zeros, 1 for the '2', and 1 for the leading zero).

All other specifiers act in this way, too. To find out how many characters are output by default for a specifier, output a value of 0 (zero) for it and count how many characters there are:

 # this outputs: '0, 0.000000, 0.000000e+00' printf("%d, %f, %e", 0, 0, 0);

You can also ask perl to count them for you:

 printf("There are %d characters\n", length(sprintf("%e", 0)));

Which should tell you there are 12 characters for 0 in scientific notation.

Padding with spaces

This is more or less the same as leading zeros, except it uses leading (or, if told, trailing) spaces to complete the field width. This is useful for lining up multiple lines of data into a report, for instance (though in that case, you may also want to specify a maximum field width to truncate long values - more on that below). The syntax is just like leading zeros, but drop the leading zero:

 printf("%6s", 'foo');  # prints '   foo'

By default, leading spaces are used, so values appear to be right-aligned in their field. To reverse this, put a '-' sign before the field width:

 printf("%-6s", 'foo');  # prints 'foo   '

For numeric values with default precision, like %f and %e, act here just like they do with leading zeros. %f, for example, won't have any padding unless you put a field width of more than 8.

Precision Modifier

The precision modifier tells printf() how many digits you want after the decimal point, if its a floating point specifier. If there are more digits than you specified, the value is rounded. If there are less, zeros are used to fill the space.

 printf("%.2f", 9.333333);  # prints '9.34' printf("%.2f", 9);   # prints '9.00'

For decimal values, the precision modifier has the same effect as the '0' modifier described above:

 printf("%.3f", 7);   # prints 007

For string values, it has the nice effect of specifying a maximum field width, where it will only print out the first n characters of the string. In combonation with the field width modifier described above, you can have a well-behaved-under-all-circumstances string field.

 printf("%.3s", 'foobar');  # prints 'foo' printf("%.10s", 'foobar');  # prints 'foobar' printf("%5.5s %5.5s", 'foobar', 'baz'); # prints 'fooba   baz'

Rounding Numbers with sprintf()

Ever wanted to round a floating point number to a decimal in perl? Or round it to an arbitrary decimal place? sprintf() gives you the ability to do that.

 # this sets $foo to '3' $foo = sprintf("%d", 3.14); # this sets $bar to '7.3531' $bar = sprintf("%.4f", 7.35309);

%d specifies to convert the given value to a decimal integer. The conversion rounds as necessary. %.4f specifies to convert the value given to a floating point number with a precision to 4 decimal places, rounding the value as needed.

Octal and Hexadecimal

You can convert your decimal based values to Hexadecimal and Octal values using printf() and sprintf(). To do so, specify the conversion as %o for octal, and %x for hexadecimal. %X is equivilant to %x, except the result is printed using capital letters.

 printf("%x", 15); # prints 'f' printf("%X", 15); # prints 'F' printf("%o", 15); # prints '17'

As explained in the Format Modifiers section, using a '#' (pound sign) right after the % will convert the value to "alternate form." For %x and %X, it will prepend to the value '0x' and '0X' respectively. For %o, a single leading '0' (zero) is added. The extra characters using the # modifier are considered part of the field width.

 printf("%#x", 15); # prints '0xf' printf("%#o", 15); # prints '017' printf("%#4x", 15); # prints ' 0xf'

In the last example, the field width of 4 is specified. Since the # modifier adds two extra characters to the value, it ends up taking 3 characters in total. Thus the single leading space.

When to Use, and When Not to

While printf() is more powerful than print(), it is also less efficient and more error-prone. The printf manpage tells us not to use printf() where a simple print() would suffice, and that's good advice. You should use printf where you need the control over a value's format that printf() gives you, when you want to use field widths (and don't care much for perl's reports), and when you want to round floating point numbers.

Errors and Corrections

Please post any errors and corrections below. I'll humbly and embarassingly admit my mistake and fix it. Helpful comments would be greatly appreciated.

 

 

 

 

http://www.perlmonks.org/?node_id=20519

댓글 0

조회수 2,006

등록된 댓글이 없습니다.

C언어HOME > C언어 > 전체 목록

게시물 검색

2022년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
2021년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
2020년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
2019년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
2018년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
Privacy Policy
MCU BASIC ⓒ 2020
모바일버전으로보기