Mike Pateras
Mike Pateras

Reputation: 15015

How do you print a limited number of characters?

Sorry to put a post up about something so simple, but I don't see what I'm doing wrong here.

char data[1024];
DWORD numRead;

ReadFile(handle, data, 1024, &numRead, NULL);

if (numRead > 0)
    printf(data, "%.5s");

My intention with the above is to read data from a file, and then only print out 5 characters. However, it prints out all 1024 characters, which is contrary to what I'm reading here. The goal, of course, is to do something like:

printf(data, "%.*s", numRead);

What am I doing wrong here?

Upvotes: 17

Views: 29838

Answers (4)

Brian Roach
Brian Roach

Reputation: 76898

You're not calling printf() correctly.

int printf ( const char * format, ... );

Which means...

printf("%.5s", data);

Upvotes: 2

sjchoi
sjchoi

Reputation: 628

You are using wrong syntax for the printf statement, and the .number is only for numerical variables.

So it should be

int i;
for(i=0;i<5;i++)
   printf("%c", data[i]);

Upvotes: -3

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76531

You have your parameters in the wrong order. The should be written:

printf("%.5s", data);

printf("%.*s", numRead, data);

The first parameter to printf is the format specifier followed by all the arguments (which depend on your specifier).

Upvotes: 36

Khaled Alshaya
Khaled Alshaya

Reputation: 96859

I think you are switching the order of arguments to printf:

printf("%.5s", data); // formatting string is the first parameter

Upvotes: 5

Related Questions