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

struct Person {
char name[50];
int citNo;
float salary;
} person1;

int main() {
  strcpy(person1.name, "George Orwell");
  person1.citNo = 1984;
  person1. salary = 2500;

  printf("Name: %s\n", person1.name);// it should print Geo

  return 0;
}

I want to print only 3 character from name(Geo).Can you please suggest any way to do that.

henry
  • 11
  • 1
  • Optionally (if you're certain the name has at least 3 characters): `printf("Name: %c%c%c\n", person1.name[0], person1.name[1], person1.name[2]);` – pmg Mar 13 '22 at 09:56
  • 1
    Use the ["Ask Question"](https://stackoverflow.com/questions/ask) button to create a new question. Don't completely edit your previous question and make answers appear out of context. I've rolled back to the original question. – pmg Mar 13 '22 at 10:16
  • Does this answer your question? [Is it possible to print out only a certain section of a C-string, without making a separate substring?](https://stackoverflow.com/questions/7780809/is-it-possible-to-print-out-only-a-certain-section-of-a-c-string-without-making) – Ekrem Solmaz Mar 14 '22 at 11:53

1 Answers1

2

Use the string format specifier with precision %.3s:

printf("Name: %.3s\n", person1.name);

See also the documentation of printf, for instance in Open Group Base specification: https://pubs.opengroup.org/onlinepubs/9699919799/

August Karlstrom
  • 10,773
  • 7
  • 38
  • 60
  • i have a structure in which there is a char line[20] = "2022/03/13 11:22:33" .. so i have to format this char line as "20220313112233".. so can it be done in any way.. for (int i = 0, j; line[i] != '\0'; ++i) { while (!(line[i] >= '0' && line[i] <= '9') && !(line[i] == '\0')) { for (j = i; line[j] != '\0'; ++j) { line[j] = line[j + 1]; } line[j] = '\0'; } } – henry Mar 13 '22 at 10:06
  • getting segmentation fault error – henry Mar 13 '22 at 10:08
  • @henry: do not ask a new question in a comment box. Use the ["Ask Question"](https://stackoverflow.com/questions/ask) button – pmg Mar 13 '22 at 10:10
  • i was not able to post questions that why putting in comments section – henry Mar 13 '22 at 10:11
  • @henry You need to create a new question on Stack Overflow. – August Karlstrom Mar 13 '22 at 10:22
  • @AugustKarlstrom i have edited the question , can you please reply on that? – henry Mar 13 '22 at 10:30