Wednesday 16 November 2011

How can you get data of only a certain type, for example, only characters? in C programming

How can you get data of only a certain type, for example, only characters?

As with almost all computer science questions, the answer is, it depends on exactly what you’re doing. If, for example, you are trying to read characters from the keyboard, you can use scanf:

scanf( “ %c” , &c );

Alternatively, you can do this with some of the built-in C library functions:

c = getchar();

These options will produce basically the same results, with the use of scanf providing more safety checking for the programmer.

If you want to receive data of other types, you can use two methods. You can get the data character by
character, always making sure that the correct thing is being entered. The other method is to use scanf,
checking its return value to make sure that all fields were entered correctly. You can use the second method to simply and efficiently extract a stream of records, verifying all of them to be correct. Here is an example program that carries out this maneuver:

#include <stdio.h>
main()
{
int i,a,b;
char c;
void ProcessRecord( int, int, char );
for( i = 0 ; i < 100 ; ++ a ) /* Read 100 records */
{
if ( scanf( “ %d %d %c” , &a , &b , &c ) != 3 )
printf( “data line %d is in error.\n” );
else
ProcessRecord( a , b , c );
}
return( 0 );
}

Cross Reference:

None.

No comments:

Post a Comment