problem in string handling

#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

and
gives output

1-> enter your string
2->your string is.......

both line 1 and 2 comes at the same time...
Last edited on
scanf("%n",&n);
I presume "%n" is a typo?


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);
    }
}
Last edited on
Topic archived. No new replies allowed.