2d-String Arrays & Functions
2d-String Arrays & Functions
2d-String Arrays & Functions
Aamina Batool
2-D Character Arrays
char list[100][16];
strcpy(list[1], "Snow White");
Inputting/outputting char 2-d arrays
Suppose that you want to read and store data in list and that there is
one entry per line.
The following for loop accomplishes this task:
for (int j = 0; j < 100; j++)
cin.get(list[j], 16);
The following for loop outputs the string in each row:
for (int j = 0; j < 100; j++)
cout << list[j] << endl;
You can also use other string functions (such as strcmp and strlen)
and for loops to manipulate list.
Another way to initialize
{{'1','2','3’},
{'4','5','6’},
{'7','8','9'}};
Reading from files
Data in the input file:
30
40
50
60
70
Task: Read these integers from the file one by one (you’d
need an integer variable) and save into another file.
Reading from files
Data in the input file:
Hello World!
We gotta find a new way of greeting the world :3
Eh, Who cares!
Tasks:
a) Read these lines one by one and save them in an array. You’d need a 2d
character array to save these c-strings.
b) Once you’ve read the whole file and saved it in the array, now write the
data from this 2-D character array into an output file (in the same format as in
the input file)
Hint: use getline function to read (also remember that aggregate input/output
operations are allowed on character arrays)
Reading from files
Data in the input file:
3 45 67 90
40 6 1 3
Tasks:
a) Read the data from the file and save in two separate 1-D arrays.
b) Write the data from 2 arrays of part a in a single output file in the same
format as the input file.
c) Read the data from the file and save in a 2-D array.
d) Write the data from 2D array of part c in a single output file in the same
format as the input file.
Passing Two-Dimensional Arrays as
11
Parameters to Functions