我一直致力于创建一个C程序,给定一个数字序列(作为字符数组提供),该程序返回与输入包含的数字数量相同的X(例如input: "1234"—>输出:"XXXX"
我写的代码是:#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* getPlaceholder(char * word);
int main(){
char * myWords []={"111","22222","1113445","9"};
char ** mywords_pointer=myWords;
/*We will apply the function getPlaceholder to each of the components of the myWords array */
for (int indx=0; indx<3; indx++){
char *currentWord=*(mywords_pointer+indx);
const char *placeholder;
printf("Calling functionn");
placeholder=getPlaceholder(currentWord);
printf("The placeholder for %s is: %sn",currentWord, placeholder);
}
return 0;
}
//getPlaceholder gets a number as a string and outputs as many Xs as digits the imput number has.
const char* getPlaceholder(char * number){
char *ptr;
long wordAsNumb=strtol(number,&ptr,10);/* in order to later be able to count the number of digits the input 'number' has*/
char *currentPlaceholder=' ';//this variable is initialised and later we will later be added new Xs in case the input number has more than one digit.
"222"--> 222
' '
.X '
while (wordAsNumb>1){
size_t len=strlen(currentPlaceholder); //this is the variable which will contain the placeholder (Xs) corresponding to the input number
char *output_string=malloc(len+2); /* adds two new characters to fit a new X (to increase the number of digits the input number has) and the "