#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int n=0;
char* str=0;
printf("enter the size of string");taking the lenght of the string from user
scanf("%d",&n);
str=calloc(n,sizeof(char)); allocating memory to the string
printf("enter your string ");
fflush(stdin); b]fflusing the standard input stream.[/b]
scanf(%[^\n]s",str); it will read the string untill next line comes
free(str);
str=0;
return 0;
}
my problem is dat it takes length from user but
did not read string
fflush(stdin); // fflusing the standard input stream.
This causes undefined behavior. What did you think it was accomplishing exactly? You probably assumed it would clear out the '\n' that was left in the input stream. Making the next line: scanf("\n%[^\n]", str); would nix that little problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int n;
char* string;
printf("enter the size of the string: ");
if (1 == scanf("%d", &n) && (string = (char*)calloc(n,1)) )
{
printf("enter your string ");
scanf("\n%[^\n]", string); // this is NOT SAFE.
printf("You entered : \"%s\"", string);
free(string);
}
}