C writing to string (specific function asked)

Viewed 88

I am kind of in a pinch with searching one specific function with return type int which changes the values of a char array (string) by taking exactly 5 parametres whereas the function must not be imported from any other library with an exception of stdio.h maybe.

The source looks like in following:

#include <stdio.h>
int main() {
  char buffer [50];
  int n;

  n= // some function here ;

  printf("%s",buffer,n);
  return 0; 
}

I have been looking into many functions, but none I knew of or found match the above requirement such that I'd appreciate the help of more knowledgeable people now. Thanks in advance.

2 Answers

You have to go with functions with variable argument lists. Two such ones in stdio.h are:

int sprintf(char * restrict s, const char * restrict format, ...);
int snprintf(char * restrict s, size_t n, const char * restrict format, ...);

Note: These functions do not exactly take five arguments as you specified in your question. They take a minimum number of arguments (2 & 3 respectively) but can go way beyond 5 arguments.

which changes the values of a char array (string)

The following does what you want to char array (info):

char info[60];
char name[] = "Christopher Westburry";
char designation[] = "Learner"; 
int reputation = 72;
sprintf(info, "Welcome %s to StackOverflow!\nDesignation: %s\nReputation: %d",
    name, designation, reputation);
printf("%s", info);

Skimming Appendix B of the C Standard, I don't see anything that takes exactly 5 arguments and returns an int.

OTOH stdio.h is full of functions that return an int and take a variable number of arguments in the scanf and printf family. Once can contrive something. Since buffer is uninitialized, and the code wants to print it, presumably we're going to read something into it from stdin. That probably means some contrived scanf call.

#include <stdio.h>
int main() {
  char buffer [50];
  int n;

  // Same as
  // n = scanf("%40s", buffer);
  n = scanf(
      "%10s%10s%10s%10s",
      buffer,
      &buffer[10],
      &buffer[20],
      &buffer[30]
  );

  // printf("%s",buffer,n);
  printf("'%s' %d\n",buffer,n);
  return 0; 
}

If that's the answer they expect, this exercise is pretty pointless.

Note that the printf in the original code has a bug where it's passed in too many arguments. Maybe that's a clue and this is supposed to be some clever use of Undefined Behavior?

Related