#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2

    Help with batch mode


    I made my first attempt at input direction and failed.
    I want to know whether I made a mistake with the code or the way I executed the program.

    This is the code:
    Code:
    #include <stdio.h>
    
    int main()
    {
        FILE *inp;
        int sum = 0,
            score,
            input_status; // status value returned by fscanf
        inp = fopen("scores.txt", "r");
    
        printf("Scores\n");
    
        input_status = fscanf(inp, "%d", &score);
        while (input_status != EOF)
        {
            printf("%5d\n", score);
            sum += score;
            input_status = fscanf(inp, "%d", &score);
        }
    
        printf("\nsum of scores is %d\n", sum);
        fclose(inp);
    }
    For the execution, I used cmd.exe instead of the normal route through the compiler.

    This is what I entered:

    And this is what I got:


    The contents of scores.txt is:
    Code:
    55
    33
    77
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    If you're trying to do input redirection you don't need to open the file in the program. You would write your program to use the console, the redirection would then use the file for the input instead of getting the input from the console.

    See this WIKI article for more information on redirection.

    Jim
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2
    If you're trying to do input redirection you don't need to open the file in the program.
    So I changed my code to
    Code:
    #include <stdio.h>
    
    int main()
    {
        int sum = 0,
            score,
            input_status; // status value returned by fscanf
    
        printf("Scores\n");
    
        input_status = scanf("%d", &score);
        while (input_status != EOF)
        {
            printf("%5d\n", score);
            sum += score;
            input_status = scanf("%d", &score);
        }
    
        printf("\nsum of scores is %d\n", sum);
    }
    which apparently is a mistake, because executing in the command line led the window for the program to appear one moment and disappear the next.

    but if I omit only the line
    Code:
    inp = fopen("scores.txt", "r");
    how do I deal with
    Code:
    while (input_status != EOF)
    Edit:
    I think I now I understand what you mean.
    You meant that I would write the program with the normal printf and scanf, and then if I redirect input from the command line, the program would read input from the text file as if I had typed it, right?

IMN logo majestic logo threadwatch logo seochat tools logo