Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i call a function that has a string and an int in the header?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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_main so 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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading