Home > front end >  How to provide an input to my code in order to test it?
How to provide an input to my code in order to test it?

Time:10-02

I am trying to learn the C language by following K&R2 reference book. I wrote a program to count how many spaces, tabs and newlines are contained in a given input. (exercise 1-8 p.20)

How can I provide to this program input to test my code ?

#include<stdio.h>

main(){

    int c,ne,nt,nf;
    ne = 0;
    nt = 0;
    nf = 0;
    while((c = getchar())!=EOF){
        if (c == ' '){
            ne  ;
        }if (c== '\t'){
            nt  ;
        }if (c== '\n'){
            nf  ;
        }
    }
    printf("Input contains %d spaces, %d tabs and %d newlines.",ne,nt,nf);
}

CodePudding user response:

It depends on how you're running your program.

  1. If you're running it from the command line, the program's standard input (which is where getchar reads from) is basically your keyboard, so you can just start typing.
  2. If you're running under an IDE, it can create a new "terminal window" for your program to run in, and for you to type input in. At least for learning, such a terminal window ought to be the default, although unfortunately it seems that sometimes you have to take additional, nonobvious steps to set this up so that it will work.

When you're typing input on your keyboard, you also need a way of saying when you're done typing. You do this by typing a "control character". Under Unix, Linux, and MacOS it's control-D, and under Windows it's control-Z. (See also notes below.)

On a suitably powerful command line, you may also have various input redirection options available to you, such as reading input from a file by involving

./myprogram < filename

or taking some other program's output and "piping" it to your programs input by invoking something like

otherprogram | ./myprogram

A few more notes about control-D and control-Z:

  1. On Unix, Linux, and MacOS, you either have to make sure you're typing the control-D at the beginning of a line (that is, you have to type Enter, then control-D), or if you're not at the beginning of a line, you have to hit control-D twice.
  2. On Windows, you have to hit control-Z, then hit Enter.

(Computers can be so fussy sometimes! :-) )

Also, you should know that although typing control-D or control-Z indirectly results in an EOF value eventually squirting out as getchar's return value in your C program, you will not find that the macro EOF has a value of "control D" or "control Z". EOF is usually the value -1, and the process of turning a control character typed by you on the keyboard, into an EOF value returned by getchar in a C program, is actually a rather elaborate one.

[I've written several long writeups on that "rather elaborate process", but I can't seem to find any of them just now. If you're curious, check back in a couple days, and maybe I'll have found one, or written a new one.]

  • Related