我的文件如下:
TEST.TXT
*Node
1,2.0,3.2
2,4.1,5.2
3,5.2,6.7
4,2.0,3.2
5,4.1,5.2
6,5.2,6.7
*Element
1,1,2,3
2,3,4,6
3,5,6,4
我该如何阅读文件?要从文件中获取具有元素的矩阵:
Node[6,3]=[...]
Element[3,4]=[...]
答案 0 :(得分:0)
包含“fstream”,声明一个ifstream变量。使用var.open(fileName)并读取就像cin:I.E。 var>> STRINGVAR。
答案 1 :(得分:0)
这是一个有效的例子:
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <tuple>
int main()
{
std::ifstream file("text.txt");
std::string line;
std::vector<std::tuple<double, double, double>> node;
std::vector<std::tuple<int, int, int, int>> element;
bool isnode = false;
bool iselement = false;
while (std::getline(file, line))
{
if (line == "*Node")
{
isnode = true;
continue;
} else if (isnode)
{
std::istringstream iss(line);
double d1, d2, d3;
char c1, c2;
if((iss >> d1 >> c1 >> d2 >> c2 >> d3))
{
node.emplace_back(d1, d2, d3);
}
}
if (line == "*Element")
{
iselement = true;
isnode = false;
continue;
} else if (iselement)
{
std::istringstream iss(line);
int i1, i2, i3, i4;
char c1, c2, c3;
if((iss >> i1 >> c1 >> i2 >> c2 >> i3 >> c3 >> i4))
{
element.emplace_back(i1, i2, i3, i4);
}
}
}
std::cout << "Printing node: " << '\n';
for (auto i = node.cbegin(); i != node.cend(); ++i)
{
std::cout << std::get<0>(*i) << ", "
<< std::get<1>(*i) << ", "
<< std::get<2>(*i) << '\n';
}
std::cout << "Printing element: " << '\n';
for (auto i = element.cbegin(); i != element.cend(); ++i)
{
std::cout << std::get<0>(*i) << ", "
<< std::get<1>(*i) << ", "
<< std::get<2>(*i) << ", "
<< std::get<3>(*i) << '\n';
}
std::cout << std::endl;
}