【发布时间】:2014-04-02 06:26:55
【问题描述】:
这是我在这里的第一个问题。所以,我正在尝试制作一个函数,它从像这样“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)));
}
【问题讨论】:
-
这看起来不像 C++。不是 C++/CLI 吗?
-
根据下面的评论,是的