twitter
    Find out what I'm doing, Follow Me :)

Character String Input

Load and display the file named stringin.c for an example of reading a string variable. This program is identical to the last one except that instead of an integer variable, we have defined a string variable with an upper limit of 24 characters (remember that a string variable must have a null character at the end).

#include "/sys/stdio.h"
main( )
{
char big[25];
printf("Input a character string,up to 25 characters.\n");
printf("An X in column 1 causes the program to stop.\n");
do {
scanf("%s",big);
printf("The string is -> %s\n",big);
} while (big[0] !=’X’);
printf("End of program.\n");
}



The variable in the "scanf" does not need an&because "big" is an array variable and by definition it is already a pointer. This program should require no additional explanation.


Compile and run it to see if it works the way you except.

You probably got a surprise when you ran it because it separated your sentence into separate words. When used in the string mode of input, "scanf" reads characters into the string until it comes to either the end of a line or a blank character. Therefore, it reads a word, finds the blank following it, and displays the result. Since we are in a loop, this program continues to read words until it exhausts the DOS input buffer. We have written this program to stop whenever it finds a capital X in column 1, but since the sentence is split up into individual words, it will stop anytime a word begins with capital X. Try entering a 5 word sentence with a capital X as
the first character in the third word. You should get the first three words displayed, and the last two simply ignored when program stops.

Try entering more than 24 characters to see what the program does. It should generate an error, but that will be highly dependent on the system you are using. In an actual program, it is your responsibility to count characters and stop when the input buffer is full. You may be getting the feeling that a lot of responsibility is placed on you when writing in C. It is, but you also get a lot of flexibility in the bargain too.