What does the %u do?

Asked

Viewed 63 times

3

I’ve been doing a list exercise on strings and researched examples. One of the codes was this:

/* strlen example */

#include <stdio.h>

#include <string.h>

int main ()
{
 
char szInput[256];

  printf ("Entre com uma frase: ");

  gets (szInput);
  
printf ("A frase com que vc entrou tem %u de caracteres",(unsigned)strlen(szInput));
 
 return 0;

}

I’d like to understand what makes the %u and the following command line, (unsigned)strlen(szInput).

By the way, that code is of that website.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

2 answers

6

%u is the equivalent of %d, but it accepts numbers without signal, the u is just from unsigned. So it was used to match the final result established in the expression that will be printed.

Here comes the question why he used unsigned to convert (cast) of the result of strlen(). I don’t know, I could have used a simple int I could still use the %d.

strlen() returns a value of type size_t, then to print an integer number with or without a signal it needs a cast.

But you could have used %zu, or even %zd and not do the cast, which is something much better. The z rightly indicates that it is accepting a size instead of an integer.

Documentation of printf().

Documentation of strlen().

0

Each conversion specifier has a corresponding type of result argument defined in the C specification. The conversion directives %u and %d actually accept the same entries, as you noted, but the argument corresponding to %u must be the type unsigned int*, nay int*. That is your example should be corrected as:

unsigned int u;
int d;
sscanf ("- 2", "% u", & u);
sscanf ("- 2", "% d", & d);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.