модификаторы функции printf() (неявное задание цифры)

Модератор: Модераторы разделов

konki
Сообщения: 216

модификаторы функции printf()

Сообщение konki »

потихоньку изучаю С и вот дошел до такой задачки:
вводится, например, имя и фамилия. необходимо напечатать эти имя и фамилию, а под ними, в другой строке, количество букв, которое содержит каждое слово.
пример:

Код:

иннокентий зачеткин 10 8

причём числовое значение надо подогнать к концу каждого соответствующего слова, как показано в примере. я так понимаю, что делается это через модификаторы спецификаций преобразования printf(). например printf("%20s", var), которое создает поле в 20 единиц, если только переменная меньше 20 символов. но как быть с моим примером, где это поле постоянно зависит от входной длины данных? например для имени пустое поле будет равно 8, а для зачеткина тоже 8 (+1 пробел между словами).

спасибо за внимание
Спасибо сказали:
Аватара пользователя
serzh-z
Бывший модератор
Сообщения: 8259
Статус: Маньяк
ОС: Arch, Fedora, Ubuntu

Re: модификаторы функции printf()

Сообщение serzh-z »

Вычислить длину "иннокентия" и длину "зачёткина", на основании этих значений сформировать строку формата (для строки с числами) для printf, сделать printf с этой строкой формата.
Спасибо сказали:
konki
Сообщения: 216

Re: модификаторы функции printf()

Сообщение konki »

точно, спасибо.
Спасибо сказали:
Аватара пользователя
Folderx
Сообщения: 296
ОС: fedora, mandriva

Re: модификаторы функции printf()

Сообщение Folderx »

Всё форматируется пустое имя проверяется.

http://ifolder.ru/5180817
Спасибо сказали:
Аватара пользователя
uptime
Сообщения: 1661
Статус: Drinker with computing problems
ОС: kubuntu 8.04

Re: модификаторы функции printf()

Сообщение uptime »

man 3 printf советует следующую конструкцию:

Код: Выделить всё

printf("%*d", width, num);

успехов
The answer, my friend, is blowin' in the wind.
The answer is blowin' in the wind.
Спасибо сказали:
konki
Сообщения: 216

Re: модификаторы функции printf()

Сообщение konki »

uptime писал(а):
01.02.2008 05:35
man 3 printf советует следующую конструкцию:

Код: Выделить всё

printf("%*d", width, num);

успехов

спасибо, как раз то что нужно. пример тоже взят из мана. :) не подскажете тогда, как установить man 3 printf, когда у меня в системе есть только 1?
может какой пакет их с собой тянет? на опеннете конечно можно читать, но и локально было бы хорошо.
Спасибо сказали:
Аватара пользователя
drBatty
Сообщения: 8735
Статус: GPG ID: 4DFBD1D6 дом горит, козёл не видит...
ОС: Slackware-current

Re: модификаторы функции printf()

Сообщение drBatty »

konki писал(а):
01.02.2008 11:17
uptime писал(а):
01.02.2008 05:35
man 3 printf советует следующую конструкцию:

Код: Выделить всё

printf("%*d", width, num);

успехов

спасибо, как раз то что нужно. пример тоже взят из мана. :) не подскажете тогда, как установить man 3 printf, когда у меня в системе есть только 1?
может какой пакет их с собой тянет? на опеннете конечно можно читать, но и локально было бы хорошо.

konki писал(а):
01.02.2008 11:17
локально было бы хорошо.


я не очень понял, какая у вас ОС.
ну ладно, вот:

Код: Выделить всё

PRINTF(3)                  Linux Programmer's Manual                 PRINTF(3)

NAME
       printf,   fprintf,  sprintf,  snprintf,  vprintf,  vfprintf,  vsprintf,
       vsnprintf - formatted output conversion

SYNOPSIS
       #include <stdio.h>

       int printf(const char *format, ...);
       int fprintf(FILE *stream, const char *format, ...);
       int sprintf(char *str, const char *format, ...);
       int snprintf(char *str, size_t size, const char *format, ...);

       #include <stdarg.h>

       int vprintf(const char *format, va_list ap);
       int vfprintf(FILE *stream, const char *format, va_list ap);
       int vsprintf(char *str, const char *format, va_list ap);
       int vsnprintf(char *str, size_t size, const char *format, va_list ap);

DESCRIPTION
       The functions in the printf() family produce output according to a for‐
       mat as described below. The functions printf() and vprintf() write out‐
       put to stdout, the standard output  stream;  fprintf()  and  vfprintf()
       write  output  to  the  given  output  stream;  sprintf(),  snprintf(),
       vsprintf() and vsnprintf() write to the character string str.

       The functions vprintf(), vfprintf(), vsprintf(), vsnprintf() are equiv‐
       alent  to  the  functions  printf(),  fprintf(), sprintf(), snprintf(),
       respectively, except that they are called with a va_list instead  of  a
       variable  number  of  arguments. These functions do not call the va_end
       macro. Consequently, the value of ap is undefined after the  call.  The
       application should call va_end(ap) itself afterwards.

       These  eight  functions  write the output under the control of a format
       string that specifies how subsequent arguments (or  arguments  accessed
       via the variable-length argument facilities of stdarg(3)) are converted
       for output.

   Return value
       Upon successful return, these functions return the number of characters
       printed  (not  including  the  trailing  '\'  used  to  end  output to
       strings).  The functions snprintf() and vsnprintf() do not  write  more
       than size bytes (including the trailing '\').  If the output was trun‐
       cated due to this limit then the return value is the number of  charac‐
       ters (not including the trailing '\') which would have been written to
       the final string if enough space had been  available.  Thus,  a  return
       value  of  size  or more means that the output was truncated. (See also
       below under NOTES.)  If an output  error  is  encountered,  a  negative
       value is returned.
  Format of the format string
       The  format  string  is a character string, beginning and ending in its
       initial shift state, if any.  The format string is composed of zero  or
       more   directives:  ordinary  characters  (not  %),  which  are  copied
       unchanged to the output stream; and conversion specifications, each  of
       which results in fetching zero or more subsequent arguments.  Each con‐
       version specification is introduced by the character %, and ends with a
       conversion  specifier.  In between there may be (in this order) zero or
       more flags, an optional minimum field width, an optional precision  and
       an optional length modifier.

       The  arguments must correspond properly (after type promotion) with the
       conversion specifier. By default, the arguments are used in  the  order
       given,  where  each ‘*' and each conversion specifier asks for the next
       argument (and it is an  error  if  insufficiently  many  arguments  are
       given).   One  can  also specify explicitly which argument is taken, at
       each place where an argument is required, by writing ‘%m$'  instead  of
       ‘%'  and  ‘*m$' instead of ‘*', where the decimal integer m denotes the
       position in the argument list of the desired argument, indexed starting
       from 1. Thus,
                   printf("%*d", width, num);
       and
                   printf("%2$*1$d", width, num);
       are equivalent. The second style allows repeated references to the same
       argument. The C99 standard does not include the style using ‘$',  which
       comes  from  the  Single Unix Specification.  If the style using ‘$' is
       used, it must be used throughout for all conversions taking an argument
       and  all  width  and precision arguments, but it may be mixed with ‘%%'
       formats which do not consume an argument.  There may be no gaps in  the
       numbers  of  arguments specified using ‘$'; for example, if arguments 1
       and 3 are specified, argument 2 must also be specified somewhere in the
       format string.

       For  some  numeric  conversions  a radix character (‘decimal point') or
       thousands' grouping  character  is  used.  The  actual  character  used
       depends on the LC_NUMERIC part of the locale. The POSIX locale uses ‘.'
       as radix character, and does not have a grouping character.  Thus,
                   printf("%'.2f", 1234567.89);
       results in ‘1234567.89' in the POSIX locale,  in  ‘1234567,89'  in  the
       nl_NL locale, and in ‘1.234.567,89' in the da_DK locale.

   The flag characters
       The character % is followed by zero or more of the following flags:

       #      The  value  should be converted to an ‘‘alternate form''.  For o
              conversions, the first character of the output  string  is  made
              zero (by prefixing a 0 if it was not zero already).  For x and X
              conversions, a non-zero result has the string ‘0x' (or ‘0X'  for
              X  conversions) prepended to it.  For a, A, e, E, f, F, g, and G
              conversions, the result will always  contain  a  decimal  point,
              even  if  no digits follow it (normally, a decimal point appears
              in the results of those conversions only if  a  digit  follows).
http://emulek.blogspot.ru/ Windows Must Die
Учебник по sed зеркало в github

Скоро придёт
Осень
Спасибо сказали:
Аватара пользователя
Dudraug
Сообщения: 313
ОС: Debian lenny/sid

Re: модификаторы функции printf()

Сообщение Dudraug »

konki писал(а):
01.02.2008 11:17
uptime писал(а):
01.02.2008 05:35
man 3 printf советует следующую конструкцию:

Код: Выделить всё

printf("%*d", width, num);

успехов

спасибо, как раз то что нужно. пример тоже взят из мана. :) не подскажете тогда, как установить man 3 printf, когда у меня в системе есть только 1?
может какой пакет их с собой тянет? на опеннете конечно можно читать, но и локально было бы хорошо.


там чо то из доков к glibc. поищи найдешь.
P4-3.0, ASUS P5GD1, 1024MB OЗУ, GeForce 6600GT
Спасибо сказали: