LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Can we specify variable field width in a scanf() format string? (http://www.linuxquestions.org/questions/programming-9/can-we-specify-variable-field-width-in-a-scanf-format-string-323117/)

skie_knite007 05-13-2005 09:38 AM

Can we specify variable field width in a scanf() format string?
 
is there any way to specify variable field width in scanf().....................???????????

I ve got one more doubt........Are these auto variables stored in registers.?

Is there any diff between auto and register?

jim mcnamara 05-13-2005 10:23 AM

I may not understand what you want -

%s specifies a string (with no spaces) of any size you have
%d specifies an integer with varying numbers of numeric characters.

A register variable means the data is stored in a register,
so the object can be up to 32 bits wide on a 32 bit machine and still fit in the register.

Otherwise a register must contain a 32 bit pointer to a big object.

auto variables are the default variable:
Code:

int foo(void)
{
    char s='Y;
    int i=0;

}

s and i are both auto variables. auto variables are stored on the stack, not in registers

skie_knite007 05-13-2005 10:41 AM

Sir,
I really want to kno, if theres any way to specify something like %kc where 'k' is a variable in the scanf(). (like %3d and 3 is got from a variable)

Harmaa Kettu 05-13-2005 12:56 PM

Quote:

is there any way to specify variable field width in scanf().....................???????????
The format string can be a variable just like any other string.
A quick example (using printf instead, but scanf works the same way):
Code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  char format[6];
  int length = 10;
  int number = 123456;

  if(argc > 1)
  {
    length = atoi(argv[1]);
    if(length < 1) { length = 1; }
    if(length > 99) { length = 99; }
  }
 
  // Construct the format
  // "%%" becomes "%", "%d" is replaced with length, last "d" remains unchanged
  sprintf(format, "%%%dd\n", length);
 
  printf(format, number);
  return(0);
}

Quote:

I ve got one more doubt........Are these auto variables stored in registers.?
They can be in registers or in the stack, depending where the compiler decides to put them. You can test this yourself. Write some simple functions, compile them with "gcc -S example.c example.s" and examine the output assembler file to see where gcc puts your variables.
Quote:

Is there any diff between auto and register?
In gcc they are the same thing except that a register variable cannot have an address, so code like this:
Code:

register int foo;
do_something(&foo);

causes a warning. Other compilers, especially old ones, may actually force register variables into registers.


All times are GMT -5. The time now is 10:45 AM.