Character By Character Input of Strings --------------------------------------- Strings may be entered and output character by character in C by using the commands: getchar() and putchar(). These may be used for prompting statements that require only a 'y' or 'n' answer or simply for displaying a single character. The format for getchar() is: char getchar(); The char in front of the statement means that it is a function and is returning a value of type char. When this function is called a single character is prompted for on the keyboard and returned. An example code fragment is: while (i < 80 && (c = getchar()) != '\n') { message[i] = c; i++; } message[i] = '\0'; What this little fragment of code does is reads in a string of characters one character at a time until 80 is reached of a newline character is reached. Then it appends a null character at the end to make it a string. See Program 9-3 for a more complete example. The command putchar() has a format of: putchar(char); This allows only one character to be sent into this procedure and it will display it to the screen. For example: putchar('h'); This will display the character 'h' to the screen. Here is a sample program illustrating these commands: Sample Program -------------- #include main() { char prompt; int not_done = 1; int i; char msg[] = "sample string"; for(i=0; msg[i]!='\0'; i++) putchar(msg[i]); while (not_done) { printf("Would you like to quit (y/n)? "); if((prompt = getchar()) == 'y') not_done = 0; } } The output is: sample stringWould you like to quit (y/n)? n Would you like to quit (y/n)? Would you like to quit (y/n)? y Notice, when you type 'n' the first time, it prompts twice therafter. That is due to the fact that you must hit "return" or "enter". This is an extra key input. So, it immediately reads it in and since it is not equal to 'y' it continues to loop.