我需要创建一个函数来在用户下打印“=”,但是因为变量是用 main() 声明的,函数看不到参数

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

我需要在用户的输入下打印“=”,我不确定是使用循环还是 printf(),但是因为字符串标题是在 main() 中声明的,所以我的函数不会将其视为参数。

Error Message

//#include "stdafx.h" // Header File used VS.
#include <iostream>
//#include <iomanip> // Used to format the output.
#include <cstdlib> // Used for system().
#include <math.h> // Used for sqrt().
#include <stdio.h>  /* printf, NULL */
#include <time.h>  /* time */
using namespace std;// ?
#include <string> // Used to work with srings.

string print_title (title);

int main (){

    string title;

    cout << "Enter a title: " << endl;
    cin >> title;

    system("PAUSE"); // Pauses the program before termination.
    return 0;
}

string print_title (title){
    cout << title << endl;
    int length = title.length();
    printf("=", length);
    /*for (int i=0; i<=length, i++){
        cout << "=" << endl;
    }*/
}

您的程序中有一些错误。

首先,你声明你的函数参数而不设置参数的数据类型。通常,函数的声明格式如下:

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

在上面,输入类型是指您期望输入类型的变量或文字的数据类型。在你的例子中,它是字符串类型,但编译器不知道,因为你没有声明输入参数的数据类型

编译器不会混淆主函数中的标题变量和 print_title 函数的输入参数,因为它们都是局部变量,特定于它们所在的各个函数。任何在一个函数中声明的变量不能被另一个函数访问;它的值最多可以通过引用传递。

相反,就像我上面解释的那样,您的代码的问题存在于以下行中:

    string print_title (title){

这是因为它缺少输入参数的数据类型,在您的例子中,它是标题。您应该将代码更改为:

    string print_title (string title){

这样你就声明了输入参数的数据类型。

您的代码存在的另一个问题是以下语句:

    printf("=", length);

这个语句本身就是一个问题,因为它违反了C++的语法规则。使用此语句时,必须在输出消息中使用占位符。此占位符特定于正在传递其数据的变量的数据类型。在您的情况下,它将是以下之一:

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

我会推荐第二个,因为首先它是一种更像 C++ 风格的方法,其次,您使用 C++ 进行编码。如果您想了解有关 printf 语句中使用的占位符和其他格式说明符的更多信息,请尝试 link:Format Specifiers: Printf()

另一方面,如果你想打印等号 "length" 次(我添加这个是因为我不确定你到底想打印什么),那么是的,你会使用 for-loop。在这里查看我的:

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

这将打印“=”符号长度的次数。就像我说的,我不确定你到底想打印什么,所以我给了两个选择。另外,我用 cout 代替了 printf,因为我发现 printf() 更像是一个 c-style 行话。只是我的安慰。

希望这能回答您的问题。