Reputation: 11
I'm working on a simple two-pass assembler for the Nand To Tetris course, and everything works just fine except for reading lines. I use a getline() with a delimiter so it stops extracting data when it reaches a comment. However, instead of stop reading and going to the next line when encountering the '/' delimiter:
Stopped reading here
||
\/
Skip -> 1 / Almost a comment
Jumped to the second line -> 2
3 @NOT_A_COMMENT
it does:
Jumped here & extracted the rest of the line
|| ||
\/ \/
From here -> 1 / Almost a comment
2
3 @NOT_A_COMMENT
So I was wondering how I could do what I showed in the first example.
Here is my code as of now:
while(getline(asmFile, label, '/')){
if(label[0] == '@' || isalpha(label[0]))
instructionNum++;
else if(label[0] == '(')
symbolsMap.emplace(label.substr(1, label.find_first_of(')')-1), convertToBinary(to_string(instructionNum+1)));
}
Upvotes: 1
Views: 1277
Reputation: 118
a simple way to do achieve this is to process it line by line and then remove the comment as suggested by @Galik.
you can add a simple function which removes comment from the given line.
template <typename T>
std::string RemoveComment(std::string line, T&& c) {
const auto pos = line.find(c);
if (pos != std::string::npos) {
line = line.substr(0, pos);
}
return line;
}
while(getline(asmFile, label)){
label = RemoveComment(label,'/');
// Note: you might want to continue in case of empty string
if(lable.empty()) continue;
// do your magic
}
another method which I can think of is to use ignore.
eg. Input file
some text.
/ comment.
some other text.
code:
while(getline(asmFile, label, '/')){
// for given input label will contain "some text."
// and position indicator will point to next char after delim '/'.
/* process label */
// skip till end of line
asmFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Upvotes: 1