10/14/2009

Inputting Multiple Values

http://irc.essex.ac.uk/www.iota-six.co.uk/c/c2_printf_and_scanf.asp

Inputting Multiple Values

If you have multiple format specifiers within the string argument of scanf, you can input multiple values. All you need to do is to separate each format specifier with a DELIMITER - a string that separates variables. For convenience, the delimiter should be one character that's a punctuation mark, like a comma or a space. As a default, scanf stops reading in a value when space, tab or Enter is pressed.

Consider scanf("%d %d", &x, &y);

(Assume that x and y have been declared beforehand!).
If I entered: 1 2 and pressed Enter, 1 would get assigned to x, and 2 would get assigned to y.
But if I entered 1, 2 and pressed Enter, x would equal 1, but y won't get assigned 2 because scanf was not expecting a comma in the input string.

Now consider:

scanf("%d, %d, %d", &x,&y,&z);

If I entered 1 2 3 and pressed enter 1 would get assigned to x but 2 and 3 won't get assigned to y or z, simply because I didn't separate the numbers with commas.
Entering 1,2,3 works, but why does 1, 2, 3 also work? scanf ignores spaces, tabs and carriage returns immediately after the delimiters.
Just don't put a space, tab or carriage return before the delimiter! 1 ,2, 3 won't work.
If you want the user to press return after each number, try something along the lines as:

scanf("%d\n%d\n%d", &x,&y,&z);

Note that you shouldn't put a delimiter after the last format specifier!

10/07/2009

Reading characters with scanf()

http://www.java2s.com/Tutorial/C/0080__printf-scanf/Readingcharacterswithscanf.htm

3.2 == 請同學練習找出下列程式錯誤之處並修正

#include /* Standard Input/Output function declarations */
#include
int main( void ) {
float fRadius; /* Radius of circle */
float fArea; /* Area of circle */
/* [a] : Prompt User for "radius of circle" */
printf("============================================\n");
printf("Please input the circle radius (Radius > 0):");
scanf("%f", &fRadius);
/* [b] : Check that the radius in greater than zero */
if( fRadius <= 0 ) {
printf("ERROR >> Circle radius must be greater than zero\n");
exit (1);
}
/* [c] : Compute Area of Circle */
fPi = 4.0*atan( 2.0 );
fArea = fPi*fRadius*fRadius;
/* [d] : Print Radius and Area */
printf("Radius of Circle = %8.3f \n", fRadius );
printf("Area of Circle = %8.3f \n", fArea );
return (0);
}

3.1 == 請同學練習找出下列程式錯誤之處並修正

#define PI 3.1415926
int main( void ) {
/* [a] : Print pi with default floating point output */
printf("My First Program : PI = %f \n, PI" );
/* [b] : Now experiment with conversion specifications */
printf("My First Program : PI = %14.7f \n", PI );
printf("My First Program : PI = %14.7e \n", PI );
printf("My First Program : PI = %14.7E \n", PI );
printf("My First Program : PI = %14.7g \n", PI );
printf("My First Program : PI = %14.7G \n", PI );
printf("My First Program : PI = %-14.7f \n", PI );
printf("My First Program : PI = %-14.7e \n", PI );
}