CStrings
CStrings
Move over
• /* Encrypt */
• while( msg[i] != '\0‘ ){
▫ if( isalpha( msg[ i ] ) ) {
c = tolower( msg[ i ] ) ;
msg[ i ] = code[ c - ‘a’ ] ;
▫ }
▫ ++i;
• }
• printf("Encrypted: %s\n", msg ) ;
Arrays of Strings
• Since strings are arrays themselves, using an array
of strings can be a little tricky
• An initialized array of string constants
▫ char months[ ][ 10 ] = {
▫ “Jan”, “Feb”, “March”, “April”, “May”, “June”,
▫ “July”, “Aug”, “Sept”, “Oct”, “Nov”, “Dec”
▫ };
▫ int m;
▫ for ( m = 0; m < 12; m++ )
▫ printf( “%s\n”, months[ m ] );
Arrays of Strings (2)
• An array of 12 string variables, each 20 chars
long
▫ char names[ 12 ] [ 21 ];
▫ int n;
▫ for( n = 0; n < 12; ++n )
▫ {
▫ printf( “Please enter your name: “ );
▫ scanf( “%20s”, names[ n ] );
▫ }
gets( ) to read a line
• The gets( ) function is used to read a line of input
(including the whitespace) from stdin until the \n
character is encountered. The \n character is
replaced with the terminating \0 character.
▫ #include <stdio.h>
▫ char myString[ 101 ];
▫ gets( myString );
• See fgets.c
fgets( )
• #include <stdio.h>
• #include <stdlib.h> /* exit */
• int main ( )
• {
• double x ;
• FILE *ifp ;
• char myLine[42 ]; /* for terminating \0 */
FILE *inFile;
inFile = fopen( “myfile”, “r” );
char string[120];
while ( fgets(string, 120, inFile ) != NULL )
printf( “%s\n”, string );
fclose( inFile );
Using fgets( ) instead of gets( )
• Since fgets( ) can read any file, it can be used in
place of gets( ) to get input from the user
▫ #include <stdio.h>
▫ char myString[ 101 ];
• Instead of
▫ gets( myString );
• Use
▫ fgets( mystring, 100, stdin );
“Big Enough”
• The “owner” of a string is responsible for allocating
array space which is “big enough” to store the string
(including the null character).
▫ scanf( ), fscanf( ), and gets( ) assume the char array
argument is “big enough”
• String functions that do not provide a parameter for
the length rely on the ‘\0’ character to determine the
end of the string.
• Most string library functions do not check the size of
the string memory. E.g. strcpy
• See strings.c
28
• return 0;
• }
• /* output */
• first contains 5 chars: bobby
• last contains 5 chars: smith
• first contains 13 chars: 1234567890123
• last contains 5 chars: smith
• Segmentation fault
The Lesson
• Avoid scanf( “%s”, buffer);
• Use scanf(“%100s”, buffer); instead
• Avoid gets( );
• Use fgets(..., ..., stdin); instead
sprintf( )
• Sometimes it’s necessary to format a string in an
array of chars. Something akin to toString( ) in
Java.
• sprintf( ) works just like printf( ) or fprintf( ), but
puts its “output” into the specified character array.
• As always, the character array must be big enough.
• See sprintf.c