10 - Strings and Command Line Arguments
10 - Strings and Command Line Arguments
Fundamentals
Week 5 - Lecture 10
What did we cover last lecture?
Debugging
Characters
● Continuing characters
Strings
Note the use of %c in the printf will format the variable as a character
Helpful Functions
getchar() is a function that will read a character from input
● Newline(\n) is a character
● Space is a character
● There’s also a special character, EOF (End of File) that signifies that there’s
no more input
● EOF has been #defined in stdio.h, so we use it like a constant
● We can signal the end of input in a Linux terminal by using Ctrl-D
Working with multiple characters
We can read in multiple characters (including space and newline)
This code is worth trying out . . . you get to see that space and newline have
ASCII codes!
// reading multiple characters in a loop
int readChar;
readChar = getchar();
while (readChar != EOF) {
printf(
"I read character: %c, with ASCII code: %d.\n",
readChar, readChar
);
readChar = getchar();
}
More Character Functions
<ctype.h> is a useful library that works with characters
● There are more! Look up ctype.h references or man pages for more
information
Strings
When we have multiple characters together, we call it a string
Both of these strings will be created with 6 elements. The letters h,e,l,l,o
and the null terminator \0
h e l l o \0
Reading and writing strings
fgets(array[], length, stream) is a useful function for reading
strings
● int strlen(char *s) - return the length of the string (not including \0)
● strcpy and strncpy - copy the contents of one string into another
● strcat and strncat - attach one string to the end of another
● strcmp and variations - compare two strings
● strchr and strrchr - find the first or last occurrence of a character
● And more . . .
Command Line Arguments
Sometimes we want to give information to our program at the moment
when we run it
● This extra text we type after the name of our program can be passed into
our program as strings
Main functions that accept arguments
int main doesn't have to have void input parameters!
● We can read the strings in, but we might want to process them
int i = 1;
while (i < argc) {
total += strtol(argv[i], NULL, 10);
i++;
}
printf("Total is %d.\n", total);
}
Break Time
We're roughly halfway through COMP1511
● Or we can try another library function that grabs a whole line of text!
● fgets() will read a line from standard input
● Characters and Strings (note that we'll never need to memorise the ASCII
table to work with characters)
● Using libraries and provided functions
● Loops on strings (using the Null Terminator \0)
● Writing multiple functions and using functions within functions
● A lot of our basic C concepts like if, while and array indexing
Challenge?
You may have noticed that rhyming_amount() loops backwards . . .
● How to take information from the same line that runs the program