CSC 183 Chap-9 2
CSC 183 Chap-9 2
printf("%s", str);
printf("\n");
str[6]='\0';
printf("%s", str);
printf("\n");
printf("\n");
printf(str);
printf("\n");
str[2]=‘&';
printf(str);
printf("\n");
Printing with puts( )
The puts function is a much simpler output
function than printf for string printing.
Prototype of puts is defined in stdio.h
int puts(const char * str)
– This is more efficient than printf
Because your program doesn't need to analyze
the format string at run-time.
For example:
char sentence[] = "The quick brown fox\n";
puts(sentence);
Prints out:
The quick brown fox
Inputting Strings with gets( )
gets( ) gets a line from the standard input.
The prototype is defined in stdio.h
char *gets(char *str)
– str is a pointer to the space where gets will store the
line to, or a character array.
– Returns NULL upon failure. Otherwise, it returns str.
char your_line[100];
printf("Enter a line:\n");
gets(your_line);
puts("Your input follows:\n");
puts(your_line);
– You can overflow your string buffer, so be careful!
Inputting Strings with scanf ( )
To read a string include:
– %s scans up to but not including the “next” white
space character
– %ns scans the next n characters or up to the next
white space character, whichever comes first
Example:
scanf ("%s%s%s", s1, s2, s3);
scanf ("%2s%2s%2s", s1, s2, s3);
– Note: No ampersand(&) when inputting strings into
character arrays! (We’ll explain why later …)
Difference between gets
– gets( ) read a line
– scanf("%s",…) read up to the next space
An Example
#include <stdio.h>
int main () {
char lname[81], fname[81];
int count, id_num;
puts ("Enter the last name, firstname, ID number
separated");
puts ("by spaces, then press Enter \n");
count = scanf ("%s%s%d", lname, fname,&id_num);
printf ("%d items entered: %s %s %d\n",
count,fname,lname,id_num);
return 0;
}
The C String Library
String functions are provided in an ANSI
standard string library.
– Access this through the include file:
#include <string.h>
– Includes functions such as:
Computing length of string
Copying strings
Concatenating strings
int main() {
char str1[] = "The first string.";
char str2[] = "The second string.";
size_t n, x;
printf("%d\n", strncmp(str1,str2,4) );
printf("%d\n", strncmp(str1,str2,5) );
}
Searching Strings (1)
There are a number of searching functions:
– char * strchr (char * str, int ch) ;
strchr search str until ch is found or NULL
character is found instead.
If found, a (non-NULL) pointer to ch is returned.