我正在尝试为c++编写一个例程,读取如下输入文件,
1 12 13 0 0 1 0 INLE
2 1 12 0 0 1 0 INLE
3 11 2 0 0 1 0 INLE
4 13 11 0 0 1 0 INLE
5 2 8 0 0 2 0 OUTL
6 8 9 0 0 2 0 OUTL
7 9 10 0 0 2 0 OUTL
8 10 3 0 0 2 0 OUTL
9 4 5 0 0 3 0 SYMP
10 5 6 0 0 3 0 SYMP
11 6 7 0 0 3 0 SYMP
12 7 1 0 0 3 0 SYMP
13 14 4 0 0 4 0 WALL
14 16 14 0 0 4 0 WALL
15 15 16 0 0 4 0 WALL
16 3 15 0 0 4 0 WALL
在本例中,我必须将第二列和第三列的值赋给右边最后一列指定的条件。比如,
read the last column;
if it reads the word INLE
{
asign the values of COLUMN2 and COLUMN3 to the pointer &p_InflowNode[i];
}
if it reads the word OUTL
{
asign the values of COLUMN2 and COLUMN3 to the pointer &p_NonrefNode[i];
}
etc...
所以我的主要问题是,我如何使c++首先读取最后一列,然后决定如何处理第二列和第三列的值?
Thaks
我建议你这么做
struct CData
{
int nC1;
int nC2;
int nC3;
int nC4;
int nC5
int nC6;
int nC7;
string sMode;
friend ifstream& operator >>(ifstream&, struct& CData);
}
只需要重载输入操作符,然后声明一个结构体的对象并对其进行操作:
struct CData cObj;
ifstream ifIn;
ifIn.open("yourfile.txt");
while(ifIn)
{
ifIn>>cObj;
//now you can use the nested if and else structure here
}
我建议如果换行符一致,则在缓冲区中逐行读取文件(std::getLine),并检查结束字符串。
检查行尾
我最终是这样解决的,
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
ifstream myfile("ramp.bnd");
string Point1;
string Point2;
string Boundary;
string line,temp;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
istringstream iss(line);
iss >> temp >> Point1 >> Point2 >> temp >> temp >> temp >> temp >> Boundary;
if (Boundary == "INLE") {
cout << "Inlet condition!!"; //To add more code
}
cout << " n";
}
myfile.close();
}
else std::cout << "Unable to open file";
myfile.close();
return 0;
}