[Solved] I need to make a function to print “=” under the user, but because variable was declared with main() the parameter isn’t seen by the function [closed]


There are a few errors in your program.

Firstly, you declare your function parameter without setting the data type of the parameter. Generally, declaring a function has the following format:

    return_type function_name(input_type input_parameter, ...)
    {
        // Do whatever you want
    }

In the above, the input type refers to the data type of the variable or literal you are expecting the input type to be. In your case, it is of type string, but the compiler does not know that, because you have NOT declared the data type of the input parameter.

The compiler is not confusing between the title variable in your main function and the input parameter of the print_title function, because they both are local variables that are specific to the respective functions they are found in. Any variable declared within a function is not accessible by another function; at the most, its value can be passed by reference.

Rather, like I explained above, the problem of your code exists in the following line:

    string print_title (title){

This is because it is missing the data type of the input parameter, which, in your case, is the title. You should change your code to:

    string print_title (string title){

This way you have declared the data type of your input parameter.

Another problem that your code has is the following statement:

    printf("=", length);

This statement in itself is a problem because it violates the syntax rules of C++. When you use this statement, you must use a placeholder in your output message. This placeholder is specific to the data type of the variable whose data is being passed. In your case, it would be one of the following:

  • printf("= %d\n",length);
  • cout << " = " << length << endl;

I would recommend the second one, as firstly it is a more C++ style approach, and secondly, you are coding in C++. Try this link if you want to find out more about placeholders and other format specifiers used in the printf statement: Format Specifiers: Printf()

On the other hand, if you want to print the equal sign “length” number of times (I’m adding this cause I’m not sure what you exactly want to print), then yes, you would use a for-loop. See mine here:

    for (int i = 0; i < length; i++)
    {
        cout << "=" << endl;
    }

This will print the “=” sign length times. Like I said, I’m not sure exactly what you wanted to print out, so I gave both choices. Also, I used cout in the place of printf because I find printf() more to be a c-style lingo. Just my comfort.

Hope this answers your question.

1

solved I need to make a function to print “=” under the user, but because variable was declared with main() the parameter isn’t seen by the function [closed]