How to Specify How Many Characters of a String to Print Out Using Printf()

Is there a way to specify how many characters of a string to print out using printf()?

The basic way is:

printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");

The other, often more useful, way is:

printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");

Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.

You can also use the notation:

printf ("Here are the first 8 chars: %*.*s\n",
8, 8, "A string that is more than 8 chars");

This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:

printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);

The POSIX specification for printf() defines these mechanisms.

Strings and character with printf

If you try this:

#include<stdio.h>

void main()
{
char name[]="siva";
printf("name = %p\n", name);
printf("&name[0] = %p\n", &name[0]);
printf("name printed as %%s is %s\n",name);
printf("*name = %c\n",*name);
printf("name[0] = %c\n", name[0]);
}

Output is:

name = 0xbff5391b  
&name[0] = 0xbff5391b
name printed as %s is siva
*name = s
name[0] = s

So 'name' is actually a pointer to the array of characters in memory. If you try reading the first four bytes at 0xbff5391b, you will see 's', 'i', 'v' and 'a'

Location     Data
========= ======

0xbff5391b 0x73 's' ---> name[0]
0xbff5391c 0x69 'i' ---> name[1]
0xbff5391d 0x76 'v' ---> name[2]
0xbff5391e 0x61 'a' ---> name[3]
0xbff5391f 0x00 '\0' ---> This is the NULL termination of the string

To print a character you need to pass the value of the character to printf. The value can be referenced as name[0] or *name (since for an array name = &name[0]).

To print a string you need to pass a pointer to the string to printf (in this case name or &name[0]).

The simplest way of printing a portion of a char[] in C

You can use printf(), and a special format string:

char *str = "0123456789";
printf("%.6s\n", str + 1);

The precision in the %s conversion specifier specifies the maximum number of characters to print. You can use a variable to specify the precision at runtime as well:

int length = 6;
char *str = "0123456789";
printf("%.*s\n", length, str + 1);

In this example, the * is used to indicate that the next argument (length) will contain the precision for the %s conversion, the corresponding argument must be an int.

Pointer arithmetic can be used to specify the starting position as I did above.

[EDIT]

One more point, if your string is shorter than your precision specifier, less characters will be printed, for example:

int length = 10;
char *str = "0123456789";
printf("%.*s\n", length, str + 5);

Will print "56789". If you always want to print a certain number of characters, specify both a minimum field width and a precision:

printf("%10.10s\n", str + 5);

or

printf("%*.*s\n", length, length, str + 5);

which will print:

"     56789"

You can use the minus sign to left-justify the output in the field:

printf("%-10.10s\n", str + 5);

Finally, the minimum field width and the precision can be different, i.e.

printf("%8.5s\n", str);

will print at most 5 characters right-justified in an 8 character field.

How to repeat a char using printf?

Short answer - yes, long answer: not how you want it.

You can use the %* form of printf, which accepts a variable width. And, if you use '0' as your value to print, combined with the right-aligned text that's zero padded on the left..

printf("%0*d\n", 20, 0);

produces:

00000000000000000000

With my tongue firmly planted in my cheek, I offer up this little horror-show snippet of code.

Some times you just gotta do things badly to remember why you try so hard the rest of the time.

#include <stdio.h>

int width = 20;
char buf[4096];

void subst(char *s, char from, char to) {
while (*s == from)
*s++ = to;
}

int main() {
sprintf(buf, "%0*d", width, 0);
subst(buf, '0', '-');
printf("%s\n", buf);
return 0;
}

Is it possible to print out only a certain section of a C-string, without making a separate substring?

Is it possible to print out only the last 5 bytes of this string?

Yes, just pass a pointer to the fifth-to-the-last character. You can determine this by string + strlen(string) - 5.

What about the first 5 bytes only?

Use a precision specifier: %.5s

#include <stdio.h>
#include <string.h>
char* string = "Hello, how are you?";

int main() {
/* print at most the first five characters (safe to use on short strings) */
printf("(%.5s)\n", string);

/* print last five characters (dangerous on short strings) */
printf("(%s)\n", string + strlen(string) - 5);

int n = 3;
/* print at most first three characters (safe) */
printf("(%.*s)\n", n, string);

/* print last three characters (dangerous on short strings) */
printf("(%s)\n", string + strlen(string) - n);
return 0;
}

Print (work with) substrings in a C program

I know how to work with a pointer to the beginning of a string, but I don't know how to determine the end.

A pointer to the last character you'd like to print is a possible solution:

void vypis(const char *retezec, const char *end)
{
while (retezec <= end && *retezec != '\0')
{
putchar(*retezec);
retezec++;
}
putchar('\n');
}

int main (void)
{
char *str = NULL;
size_t capacity = 0;

getline(&str, &capacity, stdin);
vypis(str, str + 5); //prints from str[0] to str[5]
vypis(str + 1, str + 3); //prints from str[1] to str[3]
}

String printing excluding the first N characters

Start the printing in the middle:

printf("%s", &str[5]);

How to print a string with its \n characters included?

I think it's a typical case of an XY Problem: you ask about a particular solution without really focusing on the original problem first.

After making the file into a string

Why do you think you need to read the entire file in at once? That's not normally necessary.

I want to split the string by each of its line breaks so I can modify each line individually.

You don't need to print the string to do that (you wanted "to make it so it will print Hello World!\n). You don't need to modify the string. You just need to read it in line by line! That's what fgets is for:

void printFile(void)
{
FILE *file = fopen("myfile.txt", "r");
if (file) {
char linebuf[1024];
int lineno = 1;
while (fgets(linebuf, sizeof(linebuf), file)) {
// here, linebuf contains each line
char *end = linebuf + strlen(linebuf) - 1;
if (*end == '\n')
*end = '\0'; // remove the '\n'
printf("%5d:%s\\n\n", lineno ++, linebuf);
}
fclose(file);
}
}

I want to make it so it will print Hello world!\n

If you really wanted to do it, you'd have to translate the ASCII LF (that's what \n represents) to \n on output, for example like this:

#include <stdio.h>
#include <string.h>

void fprintWithEscapes(FILE *file, const char *str)
{
const char *cr;
while ((cr = strchr(str, '\n'))) {
fprintf(file, "%.*s\\n", (int)(cr - str), str);
str = cr + 1;
}
if (*str) fprintf(file, "%s", str);
}

int main() {
fprintWithEscapes(stdout, "Hello, world!\nA lot is going on.\n");
fprintWithEscapes(stdout, "\nAnd a bit more...");
fprintf(stdout, "\n");
}

Output:

Hello, world!\nA lot is going on.\n\nAnd a bit more...

Printf() - printed characters limit

Well, if you print with the format specifier %d, which indicates a integer number, of course your maximum printable number would be INT_MAX. But your example is wrong. You are trying to tell it to print INT_MAX digits on a number, but that, of course, far exceeds the actual numerical value INT_MAX.

As to why your example fails, I suppose printf() stores the amount of digits to print in an integer number itself.

Using printf with a non-null terminated string

There is a possibility with printf, it goes like this:

printf("%.*s", stringLength, pointerToString);

No need to copy anything, no need to modify the original string or buffer.



Related Topics



Leave a reply



Submit