Reputation: 7491
How do I check the length of next line without extracting it from cin?
I have the input data in following form:
A
-B
--*
--C
-D
--E
---*
---F
0
And I have a recursive function to Build a tree from it.
TreeNode* BuildTree() {
string line;
getline(cin, line);
char id = line[line.size() - 1];
if (id == '0') return NULL;
TreeNode* n = (id == '*') ? NULL : new TreeNode(id, NULL, NULL);
if (/* This line's size less than next line's size */) {
n->left = BuildTree();
n->right = BuildTree();
}
return n;
}
Upvotes: 0
Views: 223
Reputation: 17936
Write your code so that you're one line ahead. Then your if-statement becomes:
if (/* this line's size is greater than the previous line's size */) {
....
}
Alternately, if you can afford the memory (and likely you can), slurp the entire file into a vector<string>
and then recurse on that.
Upvotes: 3