Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out dash or dot using fprintf/printf?

Tags:

c++

c

text

printf

As of now I'm using below line to print with out dot's

fprintf( stdout, "%-40s[%d]", tag, data);

I'm expecting the output would be something like following,

Number of cards..................................[500]
Fixed prize amount [in whole dollars]............[10]
Is this a high winner prize?.....................[yes]

How to print out dash or dot using fprintf/printf?

like image 215
Thi Avatar asked Jan 16 '09 18:01

Thi


People also ask

How do I print a symbol in printf?

Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use '%%'.

What is %f in printf?

The f in printf stands for formatted, its used for printing with formatted output.

What does %s mean in fprintf?

Below are several examples of printing information from variables using fprintf. Notice the use of %s to print a string, and %d to print an integer, and %f to print a number with a decimal (a floating point number).

How do I print %d output?

printf("%%d") , or just fputs("%d", stdout) . Save this answer.


2 Answers

A faster approach:

If the maximum amount of padding that you'll ever need is known in advance (which is normally the case when you're formatting a fixed-width table like the one you have), you can use a static "padder" string and just grab a chunk out of it. This will be faster than calling printf or cout in a loop.

static const char padder[] = "......................"; // Many chars

size_t title_len = strlen(title);
size_t pad_amount = sizeof(padder) - 1 - title_len;

printf(title); // Output title

if (pad_amount > 0) {
    printf(padder + title_len); // Chop!
}

printf("[%d]", data);

You could even do it in one statement, with some leap of faith:

printf("%s%s[%d]", title, padder + strlen(title), data);
like image 180
Ates Goral Avatar answered Sep 20 '22 15:09

Ates Goral


You can easily do this with iostreams instead of printf

cout << setw(40) << setfill('.') << left << tag[i] << '[' << data[i] << ']' << endl;

Or if you really need to use fprintf (say, you are passed a FILE* to write to)

strstream str;
str << setw(40) << setfill('.') << left << tag[i] << '[' << data[i] << ']' << endl;
printf(%s", str.str());
like image 31
KeithB Avatar answered Sep 20 '22 15:09

KeithB