#include <stdio.h>
#include <string.h>
/*
* This is a plain C version of the C++ string example. It contains several
* things which I may not explain fully, and is mostly to show that using
* strings in plain C is ... special.
*
* Plain C strings are fixed length, and this program sets a limit of 100,
* so the semantics will differ from the C++ one if you enter long string.
*/
int main()
{
// This declares line as an array of 100 chars, which can
// store a string of size 0 to 99. The extra byte is needed
// for a terminator, which is a zero byte. Fgets reads a line
// much as getline, but if the line has more than characters
// than line can hold, it just stops reading, leaving the
// remaining characters. Also, it leaves the \n in the
// string, which I have to get rid of. Stdin is the plain C
// equivalent of cin, but in most cases itis also the default
// for reading.
char line[100];
printf("Please enter a line:\n> ");
fgets(line, sizeof line, stdin);
line[strlen(line)-1] = 0; // This removes the last character.
// Again, read a word, this time using scanf. Scanf %s is similar
// to reading a string with cout >>, in that it skips leading
// spaces and reads a non-blank string. Unlike all other types,
// arrays do not need an & on the variable.
char word[100];
printf("Please enter a single word: ");
scanf("%s", word);
// Printf uses %s for a string.
printf("You entered %s and %s\n", word, line);
// Plain C strings can be compared with the strcmp() utility, which
// returns negative, zero, or positive much like Java .compareTo().
if(strcmp(word,"wombat") == 0)
printf("You entered \"wombat\". My favorite word!\n");
// The find operation searches for one string in another, and returns
// the position, or NULL to indicate not found. The position is a
// pointer, which is a pointer, the memory address of the found string.
char *loc = strstr(line, word);
if(loc == NULL)
printf("Your word is not in your line. Oh well.\n");
else
printf("Your word is at %d in your line.\n", loc - line);
// Plain C strings are arrays of characters, terminated by character 0.
for(int i = 0; word[i] != 0; ++i) {
printf("-%c- ", word[i]);
}
printf("\n");
}
Plain C doesn't actually have a string type. Strings are represented
by arrays of characters. Like all plain C arrays, they are fixed size,
and the string cannot be longer than the pre-chosen size of the array it
is stored in. Strings consist of characters terminated with a zero byte,
so an array of size n can hold up to length n-1, since
the extra byte is needed for the terminator
There are several library operations available, which have a
rather inconsistent interface. Also, strings, being arrays, are
can silently overflow and cause all sorts of problems if not
used carefully. We will discuss this subject later when we cover
arrays.