Friday 27 September 2013

Input Redirection: Add the numbers in a text file


Suppose someone asks us to write a program to add some numbers. The numbers are given to us in a text file saved as so:

1,2,3,4,5,6,7,8,9,10

We could write a program to accept keyboard input that will accept the numbers one by one and finally display the result. These are just ten numbers.

Code:

#include <stdio.h>
#include <conio.h>

int main()
{
    int x,y=0;

    printf("Enter the numbers (any alphabet to calculate total): \n");

    //the next line will run as long as scanf is able to read one input
    while(scanf("%i,",&x)==1)
    {
        y=y+x;
    }
    printf("The total is %i",y);
    getch();
    return 0;
}


When we run the program, we can enter the numbers, pressing enter after each. When we enter an alphabet, it will display the total of the numbers entered.


How about if there were 50 or more numbers....it would get a bit taxing to enter the numbers one by one. .

Suppose the numbers are in a file called 'AddThese.txt'. We have a program that will accept keyboard input and display the sum total of the input numbers.
Since they are already typed out in a text file, we can inject the file into the program using the command line. We use the < 'redirection operator' I think they are called.

This command has to be executed from the DOS prompt. Both the program and the text file has to be in the same folder. My program 'Test.exe' and the text file 'AddThese.txt' (which contains the text 1,2,3,4,5,6,7,8,9,10) are both in the same folder (C:\Test\). If they are not, you have to include the complete path in the program parameter, like 'test <c:\users\JohnSmith\desktop\addthese.txt'.



All I did was run the program with the '<addthese.txt' added to the program name and it accepted the input from the text file and displayed the result.


P.S: I finally found 'The C Programming Language' by Kernighan & Ritchie on Amazon (My country's Amazon site, so I could actually order it without chopping off an arm and a leg to pay for it). It should reach me within the week. Although I doubt I'll understand it, I'm excited at the prospect of having it on my bookshelf...the MUST HAVE C BOOK...finally mine...Mua-ha-ha-ha-ha!

2 comments: