我在VS c ++ / cli中有一个String
数组,并希望将其转换为float
。你能帮帮我怎么办?
我尝试使用循环来完成它,但我想知道最简单的方法和有效的方法。
array<String^>^ Nettemprature = getDataString("Temp.csv", 11);
float Nettemp[50];
int n=0;
ifstream myfile ("Temp.csv");
if (myfile.is_open())
{
while ( myfile.good() )
{
x=x+1;
getline(myfile,Nettemprature[n]);
Nettemp[n] = (float)(Convert::ToDouble(Nettemprature[n]));
...
}
...
}
答案 0 :(得分:1)
如果我试图在C ++ / CLI中将.csv文件(所有浮点数)读入数组,我会这样做:
#include "stdafx.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Diagnostics;
using namespace System::IO;
using namespace System::Linq;
float StringToFloat(String^ str)
{
return float::Parse(str);
}
int main(array<System::String ^> ^args)
{
Func<String^, float>^ stringToFloat = gcnew Func<String^, float>(StringToFloat);
array<wchar_t,1>^ arr_chrSeps = { '\t', ',', '\n', '\r', ' ' };
array<float, 1>^ arr_fltData =
Enumerable::ToArray(
Enumerable::Select<String^, float>(
File::ReadAllText("c:/science/managed/ReadCsvToFloatArray/Floats.csv")
->Split(arr_chrSeps, StringSplitOptions::RemoveEmptyEntries), stringToFloat));
Debug::WriteLine("There are {0} total floats in the list.",
Enumerable::Count<float>(arr_fltData));
Debug::WriteLine("There are {0} distinct floats in the list.",
Enumerable::Count<float>(
Enumerable::Distinct<float>(arr_fltData)));
return 0;
}