我不知道如何调用自己的函数!C++

I don't know how to call my own function! C++

本文关键字:自己的 函数 C++ 调用 何调用 我不知道      更新时间:2023-10-16

这是我的第一个问题。因此,我正在尝试创建一个函数,该函数从像"5 5 4 2"这样的文本框中获取数字,并将它们分成单独的整数,然后计算平均值。到目前为止,我所做的是这样的:

double prosjek(string a)
    {
    string razmak = " "; //the string separator, space between the numbers
    string token = a.substr(0, a.find(razmak)); //finds those separators in the textbox
    size_t pos = 0; //sets the position to zero
    int suma=0; //initializes the sum
    int brojac=0; //initializes the counter
    while ((pos = a.find(razmak)) != std::string::npos) { //loops through string and separates the numbers
        token = a.substr(0, pos);
        int numb;
        istringstream ( token ) >> numb;
        suma+=numb;
        a.erase(0, pos + razmak.length());
        brojac++;
    }
    double prosjek=suma/brojac;
    return prosjek; //returns the average
}

我不知道如何为特定的文本框调用此函数。我试过这个:

txtAverage->Text=prosjek(txtWithNumbers->Text->ToString);

但是我从智能感知收到此错误消息:错误 1 错误 C3867:"系统::字符串::ToString":函数调用缺少参数列表;使用"&System::String::ToString"创建指向成员的指针

编辑:

更新的代码(仍需要修复):

string RefStringToNativeString(System::String const^ s)
        {
        return msclr::interop::marshal_as<std::string>(s);
        }
String^ NativeStringToRefString(const std::string& s)
        {
        System::String^ result = gcnew System::String(s.c_str());
        return result;
        }
string prosjek(string a)
    {
        string razmak = " ";
        string token = a.substr(0, a.find(razmak));
        size_t pos = 0;
        int suma=0;
        int brojac=0;
        while ((pos = a.find(razmak)) != std::string::npos) {
            token = a.substr(0, pos);
            int numb;
            istringstream ( token ) >> numb;
            suma+=numb;
            a.erase(0, pos + razmak.length());
            brojac++;
        }
        double pr=suma/brojac;
        return pr.ToString();
    }

private: System::Void btnIzrPr_Click(System::Object^  sender, System::EventArgs^  e) {
    txtAverage->Text = NativeStringToRefString(prosjek(RefStringToNativeString(txtWithNumbers->Text)));
}

您实际上是在C++/CLI 中编码,而不是在C++中编码。并且您正在尝试从 .net 托管引用字符串转换为C++字符串。这样做是这样的:

#include <msclr/marshal_cppstd.h>
std::string RefStringToNativeString(System::String^ s)
{
    return msclr::interop::marshal_as<std::string>(s);
}

之后,您将面临将双精度转换为托管引用字符串。好吧,让我们假设您可以将双精度转换为C++字符串。然后你需要:

System::String^ NativeStringToRefString(const std::string& s)
{
    return gcnew System::String(s.c_str());
}

您可以像这样绕过第二个函数:

txtAverage->Text = 
    prosjek(RefStringToNativeString(txtWithNumbers->Text)).ToString();

如果您真的要使用 C++/CLI,那么您可能最好使用 .net 字符串而不是 C++ 字符串来避免所有这些来回。

尝试:

txtAverage->Text = prosjek(txtWithNumbers->Text->ToString());
//                                                      ^^^^