Find the answer to your Linux question:
Results 1 to 2 of 2
I need this program to pause where it says "Enter line: " The problem is every time I run the program it goes to Print Line iv over instead of ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Sep 2011
    Posts
    2

    problem with scanf()


    I need this program to pause where it says "Enter line: " The problem is every time I run the program it goes to Print Line iv over instead of pausing for the input at Enter line.

    Code:
    #include <stdio.h>
    
    #define MAXLINE 1000
    
    int get_line(char line[], int maxline);
    int get_int();
    
    main()
    {
        int len, max;
        char line[MAXLINE];
    
        max = get_int();
        while ((len = get_line(line, MAXLINE)) > 0) {
            if (len > max)
                printf("%s", line);
            max = get_int();
        }
    }
    
    int
    get_line(char s[], int lim)
    {
        int c, i;
    
        printf("Enter line: ");
        for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
            s[i] = c;
        if (c == '\n') {
            s[i] = c;
            ++i;
        }
        s[i] = '\0';
        return i;
    }
    
    int
    get_int()
    {
        int i;
        printf("Print line if over: ");
        scanf("%d", &i);
        return i;
    }

  2. #2
    Linux Guru Lakshmipathi's Avatar
    Join Date
    Sep 2006
    Location
    3rd rock from sun - Often seen near moon
    Posts
    1,763
    I suspect the line scanf() in get_int() is creating the problem. When you type some char and press enter ('\n') ..when it goes to get_line() for loop c has the value '\n' and it breaks out of the loop.
    for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
    s[i] = c;
    if (c == '\n') {
    So I changed it from '\n' to '$'

    for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '$'; ++i)
    s[i] = c;
    if (c == '$') {
    s[i] = c;

    output-
    Print line if over: 1
    Enter line: hello$

    hello$Print line if over: 2
    Enter line: world$

    world$
    Probably you can take it from here
    First they ignore you,Then they laugh at you,Then they fight with you,Then you win. - M.K.Gandhi
    -----
    FOSS India Award winning ext3fs Undelete tool www.giis.co.in. Online Linux Terminal http://www.webminal.org

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •