In: Computer Science
#include <stdio.h>
#include <stdlib.h>
#define K 1024
/** (2pts)
* 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
#include <stdio.h>
#include <stdlib.h>
#define K 1024
/** (2pts)
* 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()
{
char str[K];
int i, num;
// read integer
printf("num: ");
scanf("%d",&num);
fgets(str,K,stdin);// read and discard \n left by scanf
// read string
printf("str: ");
fgets(str,K,stdin);
// loop num times, displaying integers from 1 to num followed by
str (containing the newline)
for(i=1;i<=num;i++)
printf("%d %s",i,str);
return 0;
}
//end of program
Output: