Good day!

There is a program that receives characters at the input and translates them into hexadecimal system. How can I change the code so that the program handles only a certain number of characters?

For example: when n = 3, the program receiving the input "Hello", would process only Hel.

#include <stdio.h> #include <stdlib.h> #include <ctype.h> int main(void) { char in[255]; char out[255]; int len; char ch = '\0'; fgets(in, sizeof(in), stdin); len = strlen(in); if(in[len-1]=='\n') in[--len] = ch; for(int i = 0; i<len; i++) { sprintf(out+i*2, "%x", in[i]); } printf("%s\n", out); } 

PS: you cannot use string.h and malloc

  • one
    do not loop to len but to the lesser of the values ​​of n or len - Mike
  • It works, thanks. - Arden
  • "you can't use string.h" - and then what do you have strlen() ? - PinkTux
  • It is impossible to string.h. Wrong - Arden
  • 2
    First of all, it is implicitly included from stdlib.h . Secondly, you still use strlen() . Third, it is possible to use string functions without connecting string.h , it is C, not C ++. And fourth, for the future - a formal ban on malloc() in many cases costs using alloca() :-) - PinkTux

2 answers 2

cannot use string.h and malloc

And then what is it?

 len = strlen(in); 

Or the requirement not to use string.h concerns only the explicit inclusion of this header in the source? And cases of implicit inclusion, or use of string functions without declarations are permissible?

But in any case, you can do without strlen() :

 for( size_t i = 0; i < n && in[i] > 0x0D; i++ ) { printf( "%02X", in[i] ); } 
  • And what to do with the string "H♀♂lo"? :) It will be handled incorrectly with you ... Or with too long a line that did not fit into in , with N even larger? (this is a hint :)) - Harry
  • And what to do with the string "H♀♂lo"? -i] - очевидно, изменить условие проверки in [i] `. Or ... - different options may be. Let the author of the question himself thinks about them. - PinkTux

It'll do? No string functions, minimum variables ...

 #include <stdio.h> int main(void) { char in[255]; const int N = 3; // Ваше ограничение fgets(in, sizeof(in), stdin); for(char * c = in; *c && (*c != '\n') && (c - in < N); c++) { printf("%02X", *c); } }