Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

ifstream - C++: How to jump to the next immediate line when reading a file?

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)));
}
question from:https://stackoverflow.com/questions/65911789/c-how-to-jump-to-the-next-immediate-line-when-reading-a-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(), '
');
}



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...