读取文件并解析输入

reading in file and parsing the input

本文关键字:输入 文件 读取      更新时间:2023-10-16

所以我有一个文件,其中前3行将始终引用"状态",其余将引用"转换"。我知道前3行始终采用相同的格式,并且在同一行的输入之间使用制表符,但"转换"的数量未知,但始终从第4行开始。

所以我通过处理"状态"

for(int i = 0; i < 3; i++){
    myFile >> junk;
    myFile >> stateNum;
    myFile >> designation;
    //make object and put in container
}

现在我需要处理"转换",所以如果我的输入文件看起来像

state 1 a
state 2 b
state 3 c
trans a b c d &
trans d s i & 3
...
trans 4 e & d g

在同一行上的所有空白都是一个选项卡的情况下,state/trans进入junk,因为我知道1-3是state,其余的是transition,所以不需要它们。我现在如何从第4行的开始并继续到文件末尾?基本上,我使用什么if条件来实现

if(???){
    myFile >> junk;
    myFile >> one;
    myFile >> two;
    ...
    myFile >> five;
    //create object and place in container
}

其中一、二、,。。五个早些时候宣布,一个,。。。,五个对应于"trans"之后的5个条目

尝试放置

myFile >> junk;
myFile >> stateNum;
myFile >> designation;

在循环之前,然后读取循环中的每个转换,这是一个while循环,因为你不知道会有多少。

正如Dieter所说,您应该使用字符串流和getline

string line;
while (getline (myFile, line)){
//this will loop until the end of the file
  stringstream line_stream(line); 
  string word; 
  while (line >> word){
  //this will loop until there are words (transitions) on the line)
  //(your code)
}