C++ getline 并忽略

c++ getline and ignore

谁能告诉我为什么当我使用 cin.ignore(0,'\n') 但当我使用 cin.ignore(100, '\n') :/

#include <iostream>

using namespace std;


main () {
  char arr[100], brr[100];
  string srr;

  cout << "Enter a string : ";
  cin.clear();
  cin.ignore(0, '\n');
  cin.getline(arr, 100);
  cin.getline(brr, 100);
  cout << "brr : " << brr << endl;
  srr = string(arr);
  cout << "Converted to string : " << srr << endl;
  string find;
  cout << "Enter something to find : ";
  getline(cin, find);
  cout << endl;
  if (srr.find(find) != string::npos)
    cout << "Found ! at " << srr.find(find) << " " << endl;
  else
    cout << "Sorry ! not found :/ \n";
}

当您写 cin.ignore(0,'\n') 时,您说的是 "Ignore the characters in the stream until you have ignored 0 characters or you reach a '\n'"。由于您告诉流最多忽略 0 个字符,因此它什么都不做。

当你写 cin.ignore(100, '\n') 时,你说的是 "Ignore the characters in the stream until you have ignored 100 characters or you reach a '\n'"。可能不会有 100 个字符,所以在下一个换行符之前,您基本上会忽略字符。如果你考虑一下,你就会忽略该行的其余部分。

来自std::ignore documentation

Extracts and discards characters from the input stream until and including delim.

...

count - number of characters to extract

当您使用 cin.ignore(0, '\n'); 时,不会提取任何内容。这是一个 do-nothing 调用。

当您使用 cin.ignore(100, '\n'); 时,所有最多 100 个字符或直到遇到 '\n' 的字符都将被提取并丢弃。