struct LLGM{
float Lat;
float Long;
};
int main ()
{
string Filename;
int count = 0;
string value;
string temp;
ifstream infile2;
Filename = "LLMGReadingsv2.csv";
infile2.open(Filename);
if(infile2.fail())
{
cout << "Error opening file" << endl;
exit(1);
}
while(!infile2.eof())
{
getline(infile2, temp, ',');
count++;
}
cout << count << endl;
cout << endl;
infile2.close();
ifstream infile;
infile.open(Filename);
LLGM *points;
points = new LLGM [count];
for (int i = 0; i < count; i++)
{
infile >> points[i].Lat;
infile >> points[i].Long;
cout << points[i].Lat;
cout << points[i].Long;
}
cout << endl;
return 0;
}
我的问题是,如何将CSV文件中读取的值分配给各个变量?
例如:
35.123445,-85.888762(文件中一行的值) 我希望逗号之前的第一个数字是Latitude,第二个值是Longitude。
非常感谢任何帮助!
答案 0 :(得分:0)
您可以创建自己的std::ctype
构面,将逗号字符解释为分隔符。然后,您可以将其填充到文件流中,并将该流的内容插入到数组中。
#include <iostream>
#include <locale>
#include <sstream>
struct my_facet : std::ctype<wchar_t>
{
bool do_is(mask m, char_type c) const
{
if ((m & space) && c == L' ') {
return false;
}
if ((m & space) && c == L',')
{
return true;
}
return ctype::do_is(m, c);
}
};
int main()
{
std::wifstream infile(Filename);
infile.imbue(std::locale(infile.getloc(), new my_facet));
for (int i = 0; i < count; ++i)
{
if ((infile >> points[i].Lat) && (infile >> points[i].Long))
{
std::wcout << points[i].Lat;
std::wcout << points[i].Long;
}
}
}
Here is a demo that uses a stringstream
instead of a file (for demonstrating purposes only).