1

I know there are many questions with similar titles, I have not found the answer to my problem in any of them.

This is part of an assingment in a C programming workshop. I need to first get an integer from the user specifying the length of a string that I get subsequently. The existing answers deal either with a situation where the maximal input size is known at compilation time or with cases where the input can be arbitrarily large (which make for very complicated solution)

My attempt:

#include <stdio.h>  
int main() {
    int n;
    scanf("%d", &n);
    char *input =(char*)malloc(sizeof(char)*(n + 1));
    fgets(input, n, stdin);
    input[n] = '\0';
    printf("%s", input);

    return 0;
}

This prints nothing, how come?

H.Rappeport
  • 517
  • 6
  • 17
  • @user3121023 Thank you. Can you think of an easy fix? – H.Rappeport Nov 10 '18 at 22:28
  • Try `fgets(input, n, stdin); printf("<%s>\n", input); fgets(input, n, stdin); printf("<%s>\n", input);` to see the effect well commented by [@user3121023](https://stackoverflow.com/questions/53244016/c-getting-a-string-from-user-with-user-defined-length#comment93373436_53244016). Easy crappy fix: use `scanf("%d%*c", &n);` Best fix is follow [@Broman](https://stackoverflow.com/questions/53244016/c-getting-a-string-from-user-with-user-defined-length#comment93373478_53244016). – chux - Reinstate Monica Nov 10 '18 at 22:29
  • 1
    The easy fix is to not use scanf – klutt Nov 10 '18 at 22:29

0 Answers0