integers and characters character strings input and output

Click here to load reader

Upload: chloe-muriel-morton

Post on 17-Jan-2016

247 views

Category:

Documents


0 download

TRANSCRIPT

Slide 1

Strings and IOStringsIntegers and CharactersCharacter StringsInput and OutputStrings3Types So FarTo date all we have seen are numeric data typesint, short, long, long long, ...float, double, ...charThe char type stores a numeric code which is translated to a character when appropriateAnd C treats them as numbersCharacters are IntegersIts easy to print the ASCII code for a characterchar ch = x;printf(code for %c = %d, ch, ch);The first placeholder print the letter that the code representsThe second placeholder prints the codeC will also allow arithmetic to be performed on char variablesThe underlying numeric codes are operatedArithmetic and CharLets say that we want to print all of the letters from A to ZWe could write 26 printf statementsprintf('A');printf('B');...Or we could do thischar ch = 'A';while(ch < 'A' + 26){printf("%c\n", ch);ch++;}Character StringsWe have used character strings in printf callse.g. printf(Hello World);It would also be useful to store character strings in variablesAnd to get user input in the form of stringsIn C a character string is a sequence of charactersStored in an arrayName and AgeLets write a program to find out the name and age of the userAnd then print them

Name and Age Programint main(){char name[20];int age;

printf("What is your name? ");scanf("%s", name);printf("What is your age? ");scanf("%d", &age);

printf("Your name is %s, and your age is %d\n", name , age);return 0;}things to notesquare bracketsno &What is your name? JennyWhat is your age? 11Your name is Jenny, and your age is 11Character ArraysThe line char name[20]; declares an array of 20 charactersA sequence in main memory with enough space for twenty charactersAn array is an ordered sequence of data elements of one typeThe brackets identify name as an array rather than a single character And 20 indicates the size of the arrayArrays and Memory...Jenny\0A sequence of 2o adjacent bytes in main memoryWhy 20 bytes?Because each character is stored in one byteWhat is the \0 in the 6th. byte?A null character to indicate the end of the stringWhy is this necessary?Because memory locations cant be empty, so it is important to distinguish between characters we want to store and garbage valuesStrings and scanfWe used scanf like this: scanf(%s, name);The format specification %s is for a stringThe variable name is not preceded by an &Remember that when using scanf it is necessary to provide the address of a variableUsing the address of operator (i.e. &)Array variables, like name, in fact contain addresses already, an array variable is a pointerWhich is why the & is not necessaryCharacters and StringsA string consists of an array containing the words in the string and the null characterConsequently, a string containing a single character is not the same as a char variable

The type of a character array is not the same as the type of a characterThat is char name[20] declares an array not a char

athe character 'a'athe string "a"\0The Null CharacterUsually we (as programmers) are not responsible for inserting the null characterThis task is performed by a function that is responsible for creating a stringSuch as scanf, for string inputNote also that functions such as printf are able to detect the null characterTo print the appropriate part of a character arrayString FunctionsThere are a number of functions that are useful when working with stringsIt can be important to know how long a character array is and how long a string isThe maximum lengthAnd the length of the string currently stored in the arrayThe sizeof and strlen functions can be used to determine this information

Finding Sizes sizeof The sizeof function can be used to find the size in bytes of any variable or typeint x = 212;double d = 2.713;char ch = 'a';char str[20];printf("sizeof(x) = %d\n", sizeof(x));printf("sizeof(d) = %d\n", sizeof(d));printf("sizeof(ch) = %d\n", sizeof(ch));printf("sizeof(str) = %d\n", sizeof(str));printf("sizeof(short) = %d\n", sizeof(short));

Finding the Size of a StringThe strlen function can be used to find the size of a string stored in character arrayThe number of characters before the null characterchar name[20];printf("What is your name? ");scanf("%s", name);

printf("char[] size = %d\n", sizeof(name));printf("size of %s = %d\n", name, strlen(name));

#define(d) StringsWhat gets printed?#define BATMAN "Bruce Wayne"int main(){ printf("size of %s = %d\n", BATMAN, strlen(BATMAN)); printf("BATMAN size = %d\n\n", sizeof(BATMAN)); return 0;}

The difference is the null character#define and StringsThe #define pre-processor directive can be used to create string constantsAs well as any other kind of constant#define SFU "Simon Fraser University"When using #define it is not necessary to specify the type of data being definedThis is because the directive is essentially replacing the constants with the dataBefore the compiler runs

#define SyntaxDefine constants using #define like this#define #define PI 3.14159#define TITLE Lord of the Rings#define DAYS 365Constants are in upper-case by conventionTo distinguish them from variablesSize ConstantsIf you want to find the size of various types they are recorded in the limits.h filee.g. INT_MAX, LONG_MAX, LLONG_MAXThis can be useful if you want to know the byte size of a type on a particular OSThere are similar constants for floats in float.hOther ConstantsA more modern approach to creating constants is to use the const modifierconst double PI = 3.14159;Unlike #define this is not a pre-processor directive so mustDeclare the type,Use assignment, andEnd in a semi-colonDefining constants with const is more flexible when dealing with projects with multiple filesInput and Output23Using printfAs weve seen the printf function can take the following arguments (i.e. input)A string requiredPlaceholders (conversion specifiers) in the stringIntroduced by the % symbolVariable or literal arguments that should match the placeholdersIf the variables dont match the placeholders then the output will be incorrectPlaceholdersPlaceholders indicate the type to be printede.g. %d for decimal integerThese can be further modified forType sizee.g. %lld specifies a long long intField width, right justified by defaulte.g. %4d specifies a minimum field width of fourPrecision used for %e, %E, and %f to indicate the number of digits to the right of the decimal placee.g. %4.2f prints a float five characters wide with two digits after the decimal placeFlags for printfOutput can be further modified by the use of flags- left justifies the outpute.g. %-20s prints a left justified string of width 20+ indicates signed values with +, or e.g. "**%+8.2f" prints a float like this: ** +123.45 indicates signed values should start either with a space, or the sign, to allow columns of signed values to line upe.g. "**% 10.3f" prints a float like this: ** 123.4560 indicates that numbers should be padded with zerose.g. "**%8d" prints an int like this: **00000123Ive printed **s to show the spacing

More About PlaceholdersWe used different placeholders to print a character and a numberConsider this common errordouble dbl = 123.1;printf("dbl = %d", dbl);The placeholder indicates how the data stored in the argument should be printedStrictly speaking it also indicates how many bytes of the argument should be accessedMismatched ConversionsIf a variable doesnt match the placeholder the output may be incorrectThe placeholder indicates two thingsThe number of bytes of an argument to look atWhat those bytes representConsider the %d placeholderIt is an instruction to look at 4 bytes of the appropriate argumentAnd interpret them as a 2s complement intConversion ExampleHere is an example of a mismatched conversion

Incidentally printing the fourth line was fun ...printf("printf(\"n1 = %%d, n2 = %%d, n3 = %%d\",n1, n2, n3);\n\n");Note that the first placeholder prints the right most 4 bytes of n1 and the second prints the left most 4 bytesprintf, and all other function calls use an area of memory called the stack...n3(4bytes)n2(4 bytes)n1(8 bytes)...1st %d2nd %d3rd %dpart of the stackPrinting Long StringsA long C statement may take up more than one lineSince the compiler ignores white spaceA string may not take up more than one lineThe compiler gives an error if a string takes up more than one lineBut printf will concatenate two strings written on two linesprintf("blah blah blah");error!printf("blah blah ""blah");OKInput With scanfSimilar to printf, scanf uses a control string with a list of argumentsThe control string contains shows the destination data types for the input stream%s, %f, %s and so onCharacters that do not match the destination types will cause problemsThe arguments contains the addresses of the variablesWhitespaceThe scanf function uses whitespace to determine that the end of input is reachedNew lines, tabs or spacesOther input functions allow whitespace to be included in input (for strings or characters)The scanf function treats input as a stream of charactersProcessing or ignoring each characterIgnored characters are left in the streamExampleHere is a code fragment to request a name and ageint age;char name[20];

printf("Enter your age, and last name: ");scanf("%d%s", &age, name);

printf("Your name is %s, and you are aged %d\n", name, age);I could have written this in two lines:scanf("%d", &age);scanf("%s", name);What should happen:

What might happen:

When a non-numeric character is reached (e) input stops for age

Then e3 was read as the name, and input stops once whitespace is encounteredCharacters In Format StringIt is permissible to put ordinary characters in the format stringThese characters must be matched exactly by the input stringe.g. scanf(%d,%d, &x, &y);scanf expects the user to type a number, a comma, and another numberI would recommend not doing this!scanf Return ValueThe scanf function returns a value, allowing for functions to detect unexpected resultsThe value is the number of items that have been successfully readint x;int chars_read;printf("Please enter a number: ");chars_read = scanf("%d", &x);printf("Items successfully read = %d\n\n", chars_read);

More LaterWe will cover more details on many of these subjects laterArraysStringsPointersMore string functionsOther input and output functions