Good day!

How when displaying, using a variable, specify the maximum number of characters that the program can display?

#include <stdio.h> int main(){ char str[10]; int n = 2; fgets(str, sizeof(str), stdin); printf("%*.*s", n, n, str); return(0); } 
  • one
    In extreme cases, deduce the characters ... Depends on what and how you are going to deduce. The line can be simply cut, for example ... - Harry

1 answer 1

If you use the printf function for output, you can write as follows:

 char s[] = "Hello"; printf( "%*.*s", 3, 3, s ); 

Or

 int n = 3; char s[] = "Hello"; printf( "%*.*s", n, n, s ); 
  • And if you enter a string from the keyboard? - Arden
  • @Arden What's the difference where the string came from? You speak about a conclusion of a line in the question, but not about input. - Vlad from Moscow
  • Yes, I myself understand that there should be no difference. Testing code with fgets. No errors, but stdout is empty. - Arden
  • @Arden Maybe you again incorrectly specified the call to fgets? You can write printf ("% *. * S \ n", n, n, s); That is, insert also the output of the newline character. - Vlad from Moscow
  • @Arden It is necessary to specify the format character s for the lines, not c. The character c indicates when to display only one character. - Vlad from Moscow