C++ 读入文件并解析输入
所以我有一个文件,其中前3行总是指状态,其余的是指转换我知道前3行总是以相同的格式,在同一行的输入之间有制表符,但转换的数量未知,但总是从第4行开始 因此,我通过C++ 读入文件并解析输入,c++,fstream,ifstream,C++,Fstream,Ifstream,所以我有一个文件,其中前3行总是指状态,其余的是指转换我知道前3行总是以相同的格式,在同一行的输入之间有制表符,但转换的数量未知,但总是从第4行开始 因此,我通过 for(int i = 0; i < 3; i++){ myFile >> junk; myFile >> stateNum; myFile >> designation; //make object and put in container } 当同一行上的
for(int i = 0; i < 3; i++){
myFile >> junk;
myFile >> stateNum;
myFile >> designation;
//make object and put in container
}
当同一行上的所有空白都是一个标签时,state/trans会变成垃圾,因为我知道1-3是state,其余的是transition,所以不需要它们。我现在如何从第4行开始,继续到文件的结尾?基本上,如果我用什么条件来做这件事呢
if(???){
myFile >> junk;
myFile >> one;
myFile >> two;
...
myFile >> five;
//create object and place in container
}
其中一,二,。。5个在前面声明,1个,…,5个对应于trans之后的5个条目
myFile >> junk;
myFile >> stateNum;
myFile >> designation;
在循环之前,然后读取循环中的每个转换,一个while循环,因为你不知道会有多少 正如Dieter所说,您应该使用stringstream和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)
}
如果逐行读取一个行字符串getline并使用当前行字符串使用istringstream解析参数呢?如果输入行的语法确实如图所示,则trans不是垃圾。不以它开头的行不能是转换,循环读取转换应该终止。@如果输入非常受控,则文本文件中不会有错误。如果这是生产代码或其他东西,我完全同意,但我知道在这种情况下格式总是正确的。我需要用垃圾、stateNum和名称循环3次,所以我可以写9次,但在循环中很好,特别是因为在循环中,我有3个if语句,这取决于名称啊,好吧,我没有足够仔细地阅读你的问题-for循环有点道理,但是使用getline三次并解析该行会更整洁。完成三个状态行的循环后,您将需要一个while循环来进行转换。
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)
}