C++读取任意分隔符文件

Talk is cheap. Show me the code.

空格分隔

text:

1
2
3
4
5
6
7
8
9
9855.1 475.4 235.3
2135.4 756.7 764.4
5433.5 123.4 543.2
3424.3 865.8 235.1
9673.6 853.9 123.6
1563.8 654.3 542.8
2746.9 324.2 243.3
4576.4 556.8 125.5
3454.5 764.1 232.8

code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

// Read space delimited text file
void ReadFile(const std::string& inPath)
{
std::ifstream inFile(inPath);
std::string line;
while (std::getline(inFile, line))
{
std::istringstream iss(line);
double X, Y, Z;

if (!(iss >> X >> Y >> Z))
{
std::cerr << "Unknown data format " << std::endl;
break;
}

std::cout << X << " " << Y << " " << Z << std::endl;
}
inFile.close();
}

其他符号分隔

text:

1
2
3
4
5
6
7
8
9
9855.1, 475.4, 235.3
2135.4, 756.7, 764.4
5433.5, 123.4, 543.2
3424.3, 865.8, 235.1
9673.6, 853.9, 123.6
1563.8, 654.3, 542.8
2746.9, 324.2, 243.3
4576.4, 556.8, 125.5
3454.5, 764.1, 232.8

code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <array>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

// Read comma delimited text file
void ReadFile(const std::string& inPath)
{
std::ifstream inFile(inPath);
std::string line;
while (std::getline(inFile, line))
{
std::istringstream iss(line);
std::array<double, 3> coord{};
std::string value;

for (size_t i = 0; i < 3; i++)
{
std::getline(iss, value, ',');
coord[i] = std::stod(value);
}

std::cout << coord[0] << "," << coord[1] << "," << coord[2] << std::endl;
}
inFile.close();
}

StackOverflow yyds!