我不知道如何调用自己的函数!C++
I don't know how to call my own function! C++
这是我的第一个问题。因此,我正在尝试创建一个函数,该函数从像"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());
// ^^^^
相关文章:
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 在C++中,我可以在定义自己的复制构造函数后跳过定义赋值运算符吗?
- 在类自己的成员函数中构造类时,如何强制类模板参数推导?
- 在这种情况下,工会成员会调用自己的析构函数吗
- 将自己的函数添加到 ifstream
- 类中的枚举在调用自己的函数时不会改变
- 继承:子项使用父虚函数而不是自己的函数
- 如何在自己的函数中最好地处理Mat中的不同数字格式
- C++我自己的函数进行向量排序
- 是否可以阻止派生类调用自己的函数?(C++)
- 我应该如何在我自己的函数中传递 boost::asio::yield_context
- 为我自己的函数执行通常的算术转换
- 如何在CMake for OpenCV中使用我自己的函数
- 我已经寻找了MPI函数Scatterv的实现,但是我发现了任何可以帮助我编写自己的函数的东西
- 导数使用基函数而不是自己的函数
- 为什么Python运行c++函数比c++通过main()函数运行自己的函数要快?
- 将此指针弱传递给其自己的函数
- 我不知道如何调用自己的函数!C++
- 如何在c++和OpenGL中配置我自己的函数