How to keep reading using cin until a blank line is reached

3k views Asked by At

I am trying to use standard input(cin) to read in inputs until a blank line is hit. I tried many times but still fail to achieve it. Can anyone help me out?

The following is the input format. Note:
1. // are comments
2. Comments can be randomly distributed after the second line in the input. So I also need to clear those comments. Not sure how to do it.
3.The first line has to be a single letter.
4.The second line has to be an integer.

A      
8      
good
great
amazing
wonderful
fantastic
terrific
//These are some random comments
brilliant
genius
stackoverflow

The following is what I have right now. I'm trying to use getline but the program just reads in the first two lines(the letter and the number). Then the programs ends. Not sure what is going wrong:

void read() {    
  vector<string> my_vec;
  char my_letter;
  cin >> my_letter;

  int my_num
  cin >> my_num;

  string current_word;
  while (getline(cin, current_word)) {
    if (current_word.empty()) {
      break;
    }
    if (current_word[0] != '/' ) {
      my_vec.push_back(current_word);
    }
  }
}
1

There are 1 answers

0
Kerrek SB On BEST ANSWER

The extraction cin >> my_num; does not extract the newline (which is whitespace, so the next getline call extracts an empty line.

Alternative ways to solve this:

  1. Always use line-based string extraction and subordinate string streams.

  2. Use std::cin >> my_num >> std::ws to gobble whitespace.

  3. Use std::cin.ignore(1, '\n') to gobble the one newline.

  4. Use a dummy std::getline(std::cin, current_word) call to gobble the one newline.