來源 :http://www.cplusplus.com/forum/general/13058/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
// Example file contents:
// -ie; Simple individual lines of 3-doubles representing
// each point's x, y, and z coordinates.
// -BUT...somebody added commas into the data file!
//
// 1.01, 2.02, 3.03
// 4.04, 5.05, 6.06
// 7.07, 8.08, 9.09
//
// etc...
//
const string points_filename("data.txt");
string CleanLine(const string& n)
{
string cleanline;
char* char_line = (char*)n.c_str();
char* token = NULL;
char* context = NULL;
char delims[] = ",\t\n";
token = strtok_s(char_line,delims,&context);
while(token != NULL)
{
cleanline += token;
cleanline += ' ';
token = strtok_s(NULL, delims, &context);
}
return cleanline;
}
int main(void)
{
ifstream in_fs(points_filename.c_str());
if ( ! in_fs) cerr << "no points file\n";
string line, cleanline;
stringstream ss;
double x, y, z;
long point_count = 0;
// Read through all the file lines, extract and display the cleaned data.
//
while (getline(in_fs, line))
{
// Clean each line.
cleanline = CleanLine(line);
// Pass the cleaned-up string into a stringstream, to parse out the data elements.
ss << cleanline;
// Stringstream will parse directly on whitespace.
ss >> x >> y >> z; // TODO: Type compatibility checking.
// Test display of output.
cout << "For point number: " << point_count
<< "\t x: " << x
<< "\t y: " << y
<< "\t z: " << z << endl;
++point_count;
}
cin.get();
cin.get();
}