I’m having trouble with why my code isn’t being called properly. I feel like I have it correct 90% of the way. My code is meant to repeat the word "n" amount of times.
string repeat(string str, int n);
int main ()
{
string repeat_main;
repeat_main = repeat("str", 5);
}
string repeat(string str, int n)
{
string repeated_str;
int i = 0;
cout << "enter the word you would like to repeat: ";
cin >> str;
cout << "how many times would you like it to repeat? ";
cin >> n;
while (i < n)
{
repeated_str += str;
i++;
}
return repeated_str;
}
I try calling the repeat function into my main function it does not display what I am looking for.
>Solution :
As far as I can tell, there are two issues with your code:
- You need to forward declare the function if you plan to define it after
main. - You need to
cout << repeat_mainso that the string is printed.
#include <string>
#include <iostream>
using namespace std;
string repeat(string str, int n);
int main ()
{
cout << repeat("str", 5);
}
string repeat(string str, int n)
{
string repeated_str;
int i = 0;
cout << "enter the word you would like to repeat: ";
cin >> str;
cout << "how many times would you like it to repeat? ";
cin >> n;
while (i < n)
{
repeated_str += str;
i++;
}
return repeated_str;
}
As noted in comments, if you’re just going to have your function prompt for input, then you can remove the useless parameters.
string repeat()
{
string repeated_str;
string str;
int n;
int i = 0;
cout << "enter the word you would like to repeat: ";
cin >> str;
cout << "how many times would you like it to repeat? ";
cin >> n;
while (i < n)
{
repeated_str += str;
i++;
}
return repeated_str;
}
Or keep those, and use them, handling the IO in your main.
string repeat(string str, int n)
{
string repeated_str;
int i = 0;
while (i < n)
{
repeated_str += str;
i++;
}
return repeated_str;
}