Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation for sprintf("%03d", 7) functionality?

Tags:

r

printf

csv

paste

I am trying to write functions in R where the aim is to read multiple .csv files. They are named as 001.csv, 002.csv, ... 332.csv.

With paste I managed to construct names 1.csv, 2.csv and so on, but I'm having difficulty with adding leading zeroes. There's a hint that the construction like sprintf("%03d", 7) is required, but I have no idea why and how this works.

So can somebody explain what the following statement can actually does?

like image 977
user3592253 Avatar asked May 18 '14 05:05

user3592253


People also ask

How does the sprintf function work?

sprintf() in C sprintf stands for "string print". In C programming language, it is a file handling function that is used to send formatted output to the string. Instead of printing on console, sprintf() function stores the output on char buffer that is specified in sprintf.

What does 03d mean?

"%03d" is a formatting string, which specifies how 7 will be printed. d stands for decimal integer (not double !), so it says there will be no floating point or anything like that, just a regular integer.

What is the difference between printf () and sprintf () in C?

The printf function formats and writes output to the standard output stream, stdout . The sprintf function formats and stores a series of characters and values in the array pointed to by buffer. Any argument list is converted and put out according to the corresponding format specification in format.


2 Answers

sprintf originally comes from C and all formatting rules are taken from it as well. See ?sprintf in R or this or this reference to learn the subject in detail. Here I'll briefly outline what's the magic behind it.

"%03d" is a formatting string, which specifies how 7 will be printed.

  • d stands for decimal integer (not double!), so it says there will be no floating point or anything like that, just a regular integer.
  • 3 shows how many digits will the printed number have. More precisely, the number will take at least 3 digits: 7 will be __7 (with spaces instead of underscores), but 1000 will remain 1000, as there is no way to write this number with just 3 digits.
  • 0 before 3 shows that leading spaces should be replaced by zeroes. Try experimenting with sprintf("%+3d", 7), sprintf("%-3d", 7) to see other possible modifiers (they are called flags).

That being said, the output from sprintf("%03d", 7) will be 007.

like image 138
tonytonov Avatar answered Oct 05 '22 20:10

tonytonov


03d will print minimum 3 digit output...if then the output is less than 3 digit it will add zeros in beginning.If output is more than single 3 digits it will simply print output. if output(%d)= 2, with %3d will will be printed as = 002

like image 30
Syed Zargham Abbas Avatar answered Oct 05 '22 19:10

Syed Zargham Abbas