Logo  

CS256 - Fundamentals of Structured Programming

Displaying exercises/e7/solution/p2.c

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

#define K	1024

/**
 * This problem is like p1, except that you should read the number using scanf()
 * and the string to print using fgets() (up to 1024 characters.) Use "num: " as
 * the prompt for the number and "str: " as the prompt for the string. Keep in
 * mind that the newline that is entered will still be in the string when
 * printing it. NOTE: After the scanf() for the number, you will need to
 * a) use fgets() to "eat" the newline that follows the number, so use fgets once
 *    (and discard the input) before printing the second prompt and reading the
 *    string.
 *  or:
 * b) Use scanf and a %c to "eat" the newline character following the number. You
 *   can do this in the same scanf that reads the number.
 * Example:
 * > ./p2
 * num: 3
 * str: Hello
 *   1 Hello
 *   2 Hello
 *   3 Hello
 */
int main(int argc, char *argv[])
{
  int num;
  char buf[K+1], c;
  
  printf("num: ");
  scanf("%d%c", &num, &c);
  printf("str: ");
  fgets(buf, K, stdin);

  for(int i=0; i < num; i++) {
    printf("%3d %s", i+1, buf);
  }
  
  return 0;
}