Dynamic line reading input

I have a program that reads from lines in a text file and saves the space delimited strings and characters to 3 variables. For instance:

1
2
3
4
5
6
7
8
9
10
ifstream fin(argv[1]);

char v1, v2;
string cmnd;

while (fin >> cmnd >> v1 >> v2) {

//do something

}


This reads from a text file in the format of:

1
2
3
add A B
add B F
breadth A


When there are potentially 3 available variables in a line, such as with "add A B", the program reads and transfers to each variable fine. However, when it reaches something like "breadth A" where there are only two potentail variables, it does not save anything and the while loop ends. How can I have it proceed as usual and just save the two variables on the line, then switch back to being able to read 3 variables afterwards?
If the syntax of your input is always
<command> <variable 0> .. <variable n>
then you could just write something that'll tokenise a string, giving you a list of strings.

https://ideone.com/QSf7wH
Last edited on
Hmmmm......I'm confused as to how I can save these to each of the three variables I have mentioned above after each line read.
Storing into those three variables is sort of highlighting a problem in your modelling. Since not all commands have two variables, making an assumption that we need two variables is bad.

It really all depends on what you want to do. You could create a struct that holds a command and a list of variables. This means that there's no constant number of variables coupled to a command.

https://ideone.com/oxweRE
closed account (48bpfSEw)
You need a parser! Programming a parser is complicate and using regular expressions too, so I wrote my own simple parser called "Reggea" ^^


1
2
3
4
5
6
7
8
9
10
11
12
TReggae Reggea;
 
// Example string to parse:
Reggea.str = "class TMyClass { "
             "public: "
             "  TClassName1 * ptrVarName1; "
             "  TClassName2 * ptrVarName2 ;"
             "};";

Reggea.word  (strClassName)  // finds a word
            .text  ("*")                    // finds the symbol *
            .word  (strVarName)     // read the next word into variable strVarName 


https://processing8.wordpress.com/2016/02/28/dfm-dateien/

Topic archived. No new replies allowed.