I am just starting out learning C. I have the K&R2 book, as well as 'C by Example'.
In the begining of the K&R2 book it says "given getchar and putchar, you can write a surprising amount of useful code without knowing anything more about input and output." And shows an example of a program that copies its input to its output one character at a time.
Code:
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
so this keeps outputting what I type in. I tryed playing around with this a bit and am finding it hard to actualy use in terms of taking input and dealing with its data in a program.
( I know scanf is avalible but I have heard its not the best practice)
so I got googling and found how to use fgets
Code:
char *word;
char buffer[256];
printf("Enter some stuff:\n");
word = fgets(buffer, 256, stdin);
if(word != NULL) {
printf("You typed : %s\n", word);
}
This seemed a little easer to use then the first example of data copying from the K&R2 book, but I dont quite understand the check its doing. I guess fgets() stores the null character after the last character read into the buffer and returns 'buffer' if everything works fine, or NULL on error or end of file. But why would you ever get an error in the first place?
Just a few questions I have on starting to learn some about C.
'The C programming language' book said that using getchar() and putchar() you could write decent programs using it for data copying and input but I dont really see how. Like could you actualy write a program using getchar() and putchar() to make a program ask for your name, and then tell you your name without having to continue in a loop like the first example? Much Thanks.
EDIT: Woops...I ment for this to be in the C part of the forum.