这是我的第一个问题。所以,我正在尝试创建一个函数,从文本框中获取数字,如“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);
但是我从IntelliSense收到此错误消息: 错误1错误C3867:'System :: String :: 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)));
}
答案 0 :(得分:3)
您实际上是使用C ++ / CLI而不是C ++编写的。您正在尝试从.net托管的ref字符串转换为C ++字符串。这样做:
#include <msclr/marshal_cppstd.h>
std::string RefStringToNativeString(System::String^ s)
{
return msclr::interop::marshal_as<std::string>(s);
}
之后,您将面临将double转换为托管引用字符串的问题。好吧,我们假设您可以将double转换为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 ++字符串来避免所有这些来回。
答案 1 :(得分:2)
尝试:
txtAverage->Text = prosjek(txtWithNumbers->Text->ToString());
// ^^^^