-2

"In a C program, How to take a (char array) i.e. a user input string(including spaces), whose length should also be a user input value ?"

In C program, I tried to take a user input value as the length for a user input string, but did not get the required output. a code snippet of the program

I expect the output to be the same string entered by the user, whose length would also be a user input value. But the actual output does not show the string, once the user enters the string length.

P raj
  • 1
  • 1
  • 6
    You'll get an answer much easier if you post the actual code here, not a link or image of the snippet. Can you also include example input/output? – Tormund Giantsbane Jan 24 '19 at 17:20
  • 2
    Don't use `gets` (it has been deperecated long time ago, 20 years or so, not quite sure). Use `fgets` and `malloc` instead. And please don't post pictures of code, but post the code as text. – Jabberwocky Jan 24 '19 at 17:33
  • Do you trust the user to **not** input 'length'=5, 'string'="five"? – pmg Jan 24 '19 at 19:00

2 Answers2

1

you need to clear the stdin buffer after your

scanf("%d",&len);
//add to clear the buffer manually after your scanf
int c;
while((c = getchar()) != '\n' && c != EOF);
char str[len+1];
fgets(str, len + 1, stdin);

plus its a bad habit to put the code like this in a picture instead of actually posting it

Spinkoo
  • 2,080
  • 1
  • 7
  • 23
1

If the length is unknown until runtime (i.e. because it is given by a user input), dynamic allocation is an option:

char *input = malloc(len + 1);
fgets(input, len + 1, stdin);

// use `input`...

free(input);
input = NULL;

Also, never use gets; it is dangerous and not supported by the latest C standard.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • OP's use of _length_ certainly does not consider the inputted `'\n'` as part of the _length_. Use `len + 1 + 1` instead to read _length_ non-\n-characters and the `'\n'`. – chux - Reinstate Monica Jan 24 '19 at 18:27