Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input for examples from Kernighan and Ritchie

Tags:

c

input

In section 1.5.2 of the 2nd ed. K&R introduce getchar() and putchar() and give an example of character counting, then line counting, and others throughout the chapter.

Here is the character counting program

#include <stdio.h>
main() {

long nc;

nc = 0;
while (getchar() != EOF)
    ++nc;
printf("%ld\n",nc);
}

where should the input come from? typing into the terminal command window and hitting enter worked for the file copying program but not for this. I am using XCode for Mac.

It seems like the easiest way would be to read a text file with pathway "pathway/folder/read.txt" but I am having trouble with that as well.

like image 929
Davis Avatar asked Jun 25 '13 23:06

Davis


1 Answers

From the interactive command line, press ctrl-D after a newline, or ctrl-D twice not after newline, to terminate the input. Then the program will see EOF and show you the results.

To pass a file by path, and avoid the interactive part, use the < redirection operator of the shell, ./count_characters < path/to/file.txt.

like image 146
Potatoswatter Avatar answered Oct 25 '22 04:10

Potatoswatter