Home > OS >  Convert int n into string of length n in C
Convert int n into string of length n in C

Time:04-24

Hell I am very new to C and wanted to learn about strings and integer conversion.

I am trying to write a function that takes an integer n, converts to a string consisting of n's of length n. And then convert that back to a string based on the nth number of the alphabet.

For example, if i enter in int 3, it will return a string of length 3, consisting of 3, so "333". And then I would like to convert this into "CCC" since it is the 3rd letter of the alphabet.

Another example would be the function takes in the integer 5, and returns "EEEEE". 5 letters of the 5th letter of the alphabet

So far this is my code:

int *num = 3;
char* buffer[sizeof(int) * 4   1];  //got this from another question
sprintf(buffer, "%d", key_num)  //turn int into char

Anyhelp would be appreciated

CodePudding user response:

#include <stdio.h>
#include <stdlib.h>

void number_to_alphabet_string(int n){

 char buffer[n];
 for(int i=0;i<n;i  ){
   buffer[i] = n   64;
   //check ASCII table the difference is fixed to 64
   printf("%c",buffer[i]);
   }
 printf("\n");}

 int main(void){
     int C = 3;
     number_to_alphabet_string(C);

     int J = 10;
     number_to_alphabet_string(J);
     return 0;
   }

exit

If you are new to a low level programming language like C and you care about it then I strongly suggest you to go through a textbook and learn it from scratch rather than combining snipets of code. In general try to keep it simple and for tasks like that don't use complex syntax and data structures, c gives you low level control of types and that's something that you need to master if you perhaps need to use it further in the future.

  • Related