Download presentation
Presentation is loading. Please wait.
1
Strings …again
2
The road so far Up until now we have been using the header file string.h to help us manipulate strings. This has made our lives easier in many ways but it also hides important information from us.
3
Strings as Arrays Recall that a string is a sequence of characters.
As such the natural structure to contains this information is an array. In C / C++ a string is actually an array of characters.
4
To properly declare a string using an array of characters:
char name[10]; Notice that we need to decide the size of the array before the program compiles. This is problematic if we don’t know how large we want the string to be.
5
Another problem is that we cannot directly assign a string to the array.
For example we cannot do the following: char name[10]; name = “bob” This is because the “bob” is not 10 characters long.
6
We can, however, have the user input the string “bob”.
Ex: char name[10]; cout << “please enter your name” <<endl; cin >> name; If the user enters a string that is longer than 10 characters than only the first 10 will be used.
7
The most important reason why we may not want to use the string variable type is because:
Most of the predefined functions in C do not accept them as parameters!
8
Ex: The fprintf command accepts parameters that include arrays of characters but does not include strings! Ex: string name=“Charles”; fprintf(file,” %s”, name); will not run Ex: char name[10]= “Charles”; fprintf(file,”%s”, name); will run
9
printf command The printf command is a C command. (But still works in C++) It performs the function as the cout command but with much more versatility. With this added versatility comes a much more complicated syntax.
10
Printf - Syntax Printf(const * char[], variables)
The printf command takes a string a the first argument. The string itself is formated in a special way that uses placeholders to represent variables.
11
Syntax (cont) Ex: char name[10]=“Charles”;
printf(“Hello my name is %s ”, name); The %s is a placeholder for a string. The subsequent arguments represent the variable we want to use to replace the place holders. The output is: “Hello my name is Charles”
12
Formatting using printf
Specifier (placeholder) Description c Character s string d Signed integer f float e Scientific notation
13
There are many other options! Read the following articles:
Then practice using these command instead of using cin and cout.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.