Hello everyone, I'm trying to figure out how to overload a function to solve the following problem:

"Write two functions with the same name (overloaded function) that print out a phrase. The first function should take a string as an argument, and print out the string once. The second function should take a string and an integer as arguments, and print out the string as many times as the integer."

I can't figure out how to get this to run though, here's the code that I have so far:

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

void print (string word)
{
	print (word);
}

void print (string word, int number)
{
	print (word, number);
}


int main(){

	string word;
	int number(0);
	char c;
		
	cout << "Please enter your word: " << endl;
	cin >> word;
	print(word);
	cout << "\n";

	cout << "Please enter a word and a number: " << endl;
	cin >> word, number;
	print (word, number);
	cout << "\n";

	return 0;
}

Any and all help would be cool!

The first function is incorrect

void print (string word)
{
	cout << word << '\n'; // display the string
}

Now do similar for second function, but this time put cout statement inside a loop.

commented: simple as that +8

Thanks! Did that and now its working but when I get to the last one with the word and integer it just spits out a 0 when I type them in and hit enter. Nothing in the code has changed except the cout statements at the top.

The second function should take a string and an integer as arguments, and print out the string as many times as the integer.

what exactly did you put in that function? Did you use a loop?

void print (string word, int number)
{
        /*create loop that will print the following string as many times as the integer passed*/
	cout << word << endl; // display the string
}

I did, but its not running the right way.
Here's the updated code.

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

void print (string word)
{
	cout << word << "\n";
}

void print (string word, int number)
{
	for (int i = 0; i < number; i++){
	cout << (word);
	}
}


int main(){

	string word;
	int number(0);
	char c;
		
	cout << "Please enter your word: " << endl;
	cin >> word;
	print(word);
	cout << "\n";

	cout << "Please enter a word and a number: " << endl;
	cin >> word, number;
	print(word);
	cout << "\n";

	return 0;
}

at line 32
try it like this

cin >> word; //receive input for word
cin >> number; //receive input for number

or simply

cin >> word >> number;

then at line 33 call the function print (word, number);

Thanks a lot! That fixed it. :)

Thanks a lot! That fixed it. :)

Good to hear... have fun programming :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.