1
#include<stdio.h>
#include<malloc.h>

int main()
{
    char *string1;
    int length;

    scanf("%d", &length);

    string1 = (char *)malloc(sizeof(char) * length);


    printf("\n Enter the First String : ");
    fgets(string1, length, stdin);

    printf("\n The First String : %s ",string1);

    free(string1);      

    return 0;
}

Can someone help me on the above code ? I trying to get the length of a string and the string as inputs. But, I am able to enter only Length of the string. After that it skips the string input part.

This is the output I am getting :

sh-4.3$ main
10

Enter the First String :
The First String :
sh-4.3$
mch
  • 9,424
  • 2
  • 28
  • 42

3 Answers3

1
  • After typing "10<enter>" the <enter> or "\n" will remain in the stdin buffer, so you have to use getchar() after the scanf to remove it.

  • Also you should #include <stdlib.h> instead of malloc.h.

  • You malloc 1 character too less, because of the 0-terminator. string1 = malloc(length + 1); will do the job, the cast is not necessary and sizeof(char) is always 1.

mch
  • 9,424
  • 2
  • 28
  • 42
0

If you need to use stdin for string input you can use fgetln. I edited you example and now it looks like that:

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

int main()
{
    char *string1;
    size_t length;

    //scanf("%d", &length);

    //string1 = (char *)malloc(sizeof(char) * length);


    printf("\n Enter the First String : ");
    //fgets(string1, length, stdin);
    string1 = fgetln(stdin, &length);
    string1[length] = '\0';

    printf("\n The First String : %s ",string1);

    free(string1);

    return 0;
}

Note: fgetln returns not a C string, you should add a NULL character to the end.

Roman Podymov
  • 4,168
  • 4
  • 30
  • 57
  • 3
    `fgetln` isn't standard. Use `fgets` instead. – Lundin Oct 24 '16 at 07:57
  • Author of the question did not wrote nothing about the compiler. I used Apple LLVM. – Roman Podymov Oct 24 '16 at 07:59
  • 2
    Since it is tagged C with no mentioning of what system that's used, you should try to answer with standard C. Particularly, there is no reason to use non-standard functions that have standard equivalents. – Lundin Oct 24 '16 at 08:02
0

The most simple answer when reading from STDIN/keyboard with the newline etc. is to just add the "\n" to the scanf, ie:

scanf("%d\n", &length);

Solves the problem ;)

PS: Beware of all the other security/buffer overflow issues of scanf

Hvisage
  • 266
  • 2
  • 9