top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Can we specify variable field width in a scanf() format string? If possible how?

+1 vote
1,883 views
Can we specify variable field width in a scanf() format string? If possible how?
posted Nov 18, 2015 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

It is possible to specify variable field width in a scanf() format string. By using %s control string. This character reads a string of variable field width up to the first white space character.

Ex: scanf(“%s”, name); // where name is a character array

All field widths are variable with scanf(). You can specify a maximum field width for a given field by placing an integer value between the ‘%’ and the field type specifier. (e.g. %64s). Such a specifier will still accept a narrower field width. The one exception is %#c where # is an integer). This reads EXACTLY # characters, and it is the only way to specify a fixed field width with scanf().

answer Nov 18, 2015 by Shivaranjini
0 votes

Yes it is possible in addition to above answer , here is an example to understand more.

int main()
{
     int x = 0;
     char y[20]  = "";

     printf("Enter an integer : ");
     scanf("%3d", &x);              //Note it will only take the first 3 digit and store it into x
     printf("number provided by you : %d\n", x);

     printf("Enter a string: ");
     scanf("%15s", y);             // Note only take maxof 15 character and store it into y
     printf("String provided by you : %s\n", y);

     return 0;
}

OutPut:

Enter an integer : 12345
number provided by you : 123      // as it  only takes the first 3 digit  because we use "%3d"
Enter a sting : HelloWorldHelloWorld
String provided by you : HelloWorldHello   //only prints the fisrt 15 char.
answer Nov 23, 2015 by Arshad Khan
Similar Questions
+5 votes

Can we realloc a string inside a structure?

struct info
{
     char name[20];
     int age;
     char address[20];
}; 

struct info d[10];

I want to realloc name, how can I do it?

...