【问题标题】:Function with arrays not working带有数组的函数不起作用
【发布时间】:2015-04-29 05:50:35
【问题描述】:

我需要制作一个具有三个功能的程序。

主函数应该调用第二个函数,将数组作为第一个参数,将数组中的元素数量作为第二个参数。

第二个函数传入一个数组和数组中的元素个数。该函数应该从用户那里获得 8 个名字,并将读取的名字的数量返回给 main。使用 return 语句来执行此操作。

在数组被第二个函数填充后,main 应该调用第三个函数,将数组作为第一个参数传递给它,第二个函数返回的值作为第二个参数。

第三个函数应该在计算机屏幕上以不同的行显示数组中的名称。第三个函数作为第一个参数传入一个数组。第二个参数是要显示的数组元素个数。

主函数有一个包含 10 个元素的数组。第二个函数传递 10 个元素的数组,但只读取 8 个元素。第二个函数读入的数字返回给 main。然后 Main 将数组和从第二个函数返回的值传递给第三个函数。

到目前为止,我的代码是:

#include <iostream>
#include <string>

using namespace std;


int main()
{
// get the names and store them in the array
int const arraySize(10);
int names = 8;          
string array[arraySize];

// send to second function
recievenames(array, arraySize);

// send to third function
displaynames(array, 8);

return 0;
}


int recievenames(string array[], int arraySize)
{
int names = 0;

// Get names.
for (int count = 0; count < 8; count++)
{
    cout << "Enter name " << (count + 1) << " of 8: ";
    cin >> array[count];

    if (count < 8)
    {
        names++;
    }
}
// Display amount of names entered.
cout << names << " received.";
}

void displaynames(string array[], int names)
{
// Display names entered in array.
for (int count = 0; count < names; count++)
{
    cout << array[count] << endl;
}
}

由于某种原因它不起作用,谁能告诉我为什么?

【问题讨论】:

  • 定义“不工作”。编译时错误?运行时间问题?
  • 你的代码不会被编译,因为函数在使用之前没有被声明。您应该在 main 之前声明函数或在 main 之前键入完整的函数减速
  • “它不工作” - 那是因为它不能编译。编译器不知道您的函数是否存在于您在main() 中调用它们的位置。你至少需要原型,或者将它们移到之前 mainrecievenames 说它返回一个值。要么提供一个,要么将结果类型更改为void。您也可以考虑使用您传递的arraySize,而不是在读取循环中硬编码一个魔术 8。

标签: c++ arrays string function


【解决方案1】:

您必须对函数原型 recievenames()displaynames() 进行前向声明,并将它们放在 main() 之前。然后就可以在main后面定义和体现函数了。

#include <iostream>
#include <string>

using namespace std;

// declare function prototypes
int recievenames(string array[], int arraySize);
void displaynames(string array[], int names);




int main()
{
// get the names and store them in the array
int const arraySize(10);
int names = 8;          
string array[arraySize];

// send to second function
recievenames(array, arraySize);

// send to third function
displaynames(array, 8);

return 0;
}

//define functions
int recievenames(string array[], int arraySize)
{
int names = 0;

// Get names.
for (int count = 0; count < 8; count++)
{
    cout << "Enter name " << (count + 1) << " of 8: ";
    cin >> array[count];

    if (count < 8)
    {
        names++;
    }
    return 0;
}
// Display amount of names entered.
cout << names << " received.";
}

void displaynames(string array[], int names)
{
// Display names entered in array.
for (int count = 0; count < names; count++)
{
    cout << array[count] << endl;
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多