Help with a program

Discussion in 'C' started by lionaneesh, Mar 24, 2010.

  1. lionaneesh

    lionaneesh Active Member

    Joined:
    Mar 21, 2010
    Messages:
    848
    Likes Received:
    224
    Trophy Points:
    43
    Occupation:
    Student
    Location:
    India
    Code:
    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
    
        int i;
        char line[100];
        char line2[100];
        
    
        printf("Enter some lines : ");
        scanf("%[^\n]",line);
        printf("2:");
        scanf("%[^\n]",line2);
    
        if((i = strlen(line)) >= 80)
        {
            printf("%s",line);
        }
        if(strlen(line2) >= 80)
        {
            printf("%s",line2);
        }
        getchar();
        return(0);
    }
    the main aim of making this program is that it will input 2 lines and output only that line that is 80 or more in length.

    errors :-
    1. There is no compile error.
    2. the second scanf(); function does not inputs.
    3. No printf funtion occurs.

    help me run this program successfully.

    thanks in advance.
     
  2. karthigayan

    karthigayan New Member

    Joined:
    Feb 19, 2010
    Messages:
    33
    Likes Received:
    0
    Trophy Points:
    0
    The problem happen by the '\n' of the line.Since it gets the input till the newline the entered '\n' will remain in the buffer .

    That '\n' will come as a input for the line2.It too get the input till the '\n' . So it comes out immediately . So you need to clear the '\n'.You can do this by getchar().

    Code:
    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
    
        int i;
        char line[100];
        char line2[100];
    
    
        printf("Enter some lines : ");
        scanf("%[^\n]",line);
        printf("2:");
        getchar(); // Will get the "\n" in the buffer
        scanf("%[^\n]",line2);
    
        if((i = strlen(line)) >= 80)
        {
            printf("%s",line);
        }
        if(strlen(line2) >= 80)
        {
            printf("%s",line2);
        }
        getchar();
        return(0);
    }
    
    But always don't use
    Code:
    scanf("%[^\n]",line2);
    
    Because it will cause the buffer overflow some times . Instead use fgets .
     
    Last edited: Mar 24, 2010

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice