如何使用 cin 继续阅读直到到达空白行

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

我正在尝试使用标准输入 (cin) 读取输入,直到出现 空白行 。我尝试了很多次,但仍然无法实现。谁能帮帮我?

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
很好
很棒
很棒
很棒
很棒
很棒
//这些是一些随机评论
brilliant
genius
Whosebug

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);
    }
  }
}

提取 cin >> my_num; 不提取换行符(这是空格,因此下一个 getline 调用提取一个空行。

解决此问题的替代方法:

  1. 始终使用基于行的字符串提取和从属字符串流。

  2. 使用std::cin >> my_num >> std::ws吞噬空格。

  3. 使用std::cin.ignore(1, '\n')吞掉一个换行符。

  4. 使用虚拟 std::getline(std::cin, current_word) 调用来吞掉一个换行符。