Hi, how do I print a string such that only a section of it gets printed, without printing it character by character?

I thought of pointer arithmetic, but that will only change the starting point of the string for you. What I want to do is to print from start to (size of string - n).

I tried this:

char c[40], *pc;
int size;

scanf("%s", c);
size = strlen(c);
pc = c + size - 4;

printf("%s\n", c - pc);

When I input "abcdefg", since pc points to "defg", I thought (c - pc) would give me "abc", but instead it gives a segfault. What should I do to just make it print "abc" without printing it char by char? Thanks!

c - pc just gives you an integer (well a ptrdiff_t actually).

Eg, given pc = &c[5]; then pc - c would get you back to 5

To answer your other question, look in the manual to figure out what such things as these do.

printf("%s\n", "hello" );
printf("%.4s\n", "hello" );
printf("%.*s\n", 4, "hello" );

you need to truncate the string at the spot where you want to stop printing. If you want the full string later then save that character in another variable and put it back after printing

char c[40], *pc, save;
int size;

scanf("%s", c);
size = strlen(c);
save = c[size-4];
// truncate the string
c[size-4] = 0;
printf("%s\n", c);
// now put it back
c[size-4] = save;
This question has already been answered. Start a new discussion instead.