It is not uncommon in programming to use an array of strings. For example, the input
processor to a database may verify user commands against an array of valid
commands. To create an array of null-terminated strings, use a two-dimensional
character array. The size of the left index determines the number of strings and the size
of the right index specifies the maximum length of each string. The following code
declares an array of 30 strings, each with a maximum length of 79 characters
char str_array[30][80];
It is easy to access an individual string: You simply specify only the left index. For
example, the following statement calls gets() with the third string in str_array.
gets(str_array[2]);
The preceding statement is functionally equivalent to
gets(&str_array[2][0]);
but the first of the two forms is much more common in professionally written
C/C++ code.
processor to a database may verify user commands against an array of valid
commands. To create an array of null-terminated strings, use a two-dimensional
character array. The size of the left index determines the number of strings and the size
of the right index specifies the maximum length of each string. The following code
declares an array of 30 strings, each with a maximum length of 79 characters
char str_array[30][80];
It is easy to access an individual string: You simply specify only the left index. For
example, the following statement calls gets() with the third string in str_array.
gets(str_array[2]);
The preceding statement is functionally equivalent to
gets(&str_array[2][0]);
but the first of the two forms is much more common in professionally written
C/C++ code.
To better understand how string arrays work, study the following short program,
which uses a string array as the basis for a very simple text editor:
/* A very simple text editor. */
#include <stdio.h>
#define MAX 100
#define LEN 80
char text[MAX][LEN];
int main(void)
{
register int t, i, j;
printf("Enter an empty line to quit.\n");
for(t=0; t<MAX; t++) {
printf("%d: ", t);
gets(text[t]);
if(!*text[t]) break; /* quit on blank line */
}
for(i=0; i<t; i++) {
for(j=0; text[i][j]; j++) putchar(text[i][j]);
putchar('\n');
}
return 0;
}
This program inputs lines of text until a blank line is entered. Then it redisplays each
line one character at a time.
which uses a string array as the basis for a very simple text editor:
/* A very simple text editor. */
#include <stdio.h>
#define MAX 100
#define LEN 80
char text[MAX][LEN];
int main(void)
{
register int t, i, j;
printf("Enter an empty line to quit.\n");
for(t=0; t<MAX; t++) {
printf("%d: ", t);
gets(text[t]);
if(!*text[t]) break; /* quit on blank line */
}
for(i=0; i<t; i++) {
for(j=0; text[i][j]; j++) putchar(text[i][j]);
putchar('\n');
}
return 0;
}
This program inputs lines of text until a blank line is entered. Then it redisplays each
line one character at a time.
No comments:
Post a Comment