Template function (with string) problem.

Hi guys, I'm doing an assignment fro my engineering class and I need a bit of help with the following assignment.

" Write a template function, print, that takes as input
an array and a variable that gives the number of elements in the array. The
function should then step through the array printing out each element and
separating the elements by a single space. The function should use templates
in that the type of the array should be a template. You should provide a driver
function that demonstrates the function on an array of doubles and an array
of strings."

I have it working for the 'int' and 'float types. I have 'char' in here " getArrayX<char>(NumEl); " but what i actually need is a array of strings as stated above.

Could somebody maybe guide me in the right direction with this please? :)

This is the .cpp file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#include <iostream>
#include <math.h>
#include <string.h>
#include "Lab8E1_1.h"

using namespace std;

int main()
{

	double NumEl;

	cout << "Enter the number of elements in the array: " <<  endl;
	cin >> NumEl;
	

	getArrayX<int>(NumEl);

	cout << endl;

	getArrayX<float>(NumEl);
	cout << endl;

	getArrayX<char>(NumEl);
	cout << endl;
	

	system("PAUSE");
	return 0;
	

};



And this is the .h file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

#include <iostream>
#include <math.h>
#include <string.h>

using namespace std;


template <class Print>
Print getArrayX (Print NumElements)
{
	int y = 0;

	Print *elements = new Print [NumElements];


	for (int x = 1; x <= NumElements; x++)
	{
	cout << "Input Element " << (x) << ":" << endl;
	cin >> elements[x];
	}


	for (int z = 1; z<=NumElements; z++)
	{
	cout << elements[z] << " ";
	}

	return 
		elements[y];
}
It looks like you're trying to modify existing code from an old assignment to do something completely different. Just start over. I promise, it isn't much code at all. To help get you started, here's a suitable driver program. You need to write the 'print' function to make this work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

//write print, which takes an array and the size of that array as parameters
//print(...)
//{
//    ...
//}

int main()
{
    double dblArray[] = { 0.0, 1.1, 2.2, 9.5, 8.4 };
    std::string strArray[] = { "Hey", "Jude", "Na na na na" };

    std::cout << "Printing array of doubles:\n";
    print<double>(dblArray, 5);

    std::cout << "\n\nPrinting array of strings:\n";
    print<std::string>(strArray, 3);
    return 0;
}
Hi Booreadley,

I really appreciate the reply thanks. :)

I actually wrote this from scratch but I wasn'y 100% sure what I was doing exactly because I find the course a bit tough.

I'll try it again with the hints you gave me.

Thanks again.
Topic archived. No new replies allowed.