logo

Функція Cin.ignore() у C++

У C++, cin.ignore() функція є важливою для вирішення проблеми, пов'язані з введенням , особливо при використанні прийом їжі і функції getline разом. Очистивши вхідний буфер і видаливши непотрібні символи, розробники можуть забезпечити належну та точну поведінку процесів введення. У цій статті ми розглянемо функції cin.ignore(). синтаксис, використання, приклади , і очікувані результати .

The потік класу функція cin.ignore(). можна використовувати для ігнорування тексту до певної кількості символів або доки не буде знайдено певний роздільник. Його синтаксис такий:

cin.ignore(n, розділювач);

найкрасивіша усмішка в світі

Синтаксис параметрів функції Cin.ignore():

n (необов'язково): Він вказує, скільки має бути символів ігнорується .

Роздільник (необов'язково): У ньому вказано a символ роздільника , після чого введення не враховуватиметься. Якщо ні зазначено , за замовчуванням 1 . Якщо нічого немає зазначено , потім символ електронного рядка ('n') використовується за замовчуванням .

Використання та робота функції Cin.ignore():

Основне призначення в функція cin.ignore(). це видалити небажані персонажі від вхідний буфер . Нове введення тепер можна прочитати, оскільки вхідний буфер очищено. Його можна використовувати за різних обставин, у тому числі після читання числового введення з прийом їжі , раніше читання рядків з getline , а також при об'єднанні окремих процедур введення.

До виконання однієї з наступних умов met, cin.ignore() читає символів із вхідного буфера та відкидає їх:

  1. Якщо 'n' символів були вказані, вони були проігноровані.
  2. Поки роздільник (якщо вказано) не було знайдено, символи не враховувалися.
  3. Коли це відбувається, вхідний буфер повний.

Залишаючи один символ

Давайте подумаємо про простий сценарій, коли нам потрібно прочитати два символи від користувача. Але нам це не потрібно перший символ ; нам потрібно лише другий . Як показано нижче, ми можемо зробити це за допомогою cin.ignore() .

 #include int main() { char secondCharacter; std::cout&lt;&gt;std::noskipws&gt;&gt;secondCharacter; std::cin.ignore(); std::cout&lt;&lt; &apos;The second character is: &apos; &lt;<secondcharacter<<std::endl; return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> Enter two characters: AB The second character is: B </pre> <p> <strong>Explanation:</strong> </p> <p>In the above example, we use <strong> <em>std::noskipws</em> </strong> to <strong> <em>stop characters</em> </strong> from reading with whitespace skipped. In order to remove the undesirable character after reading the first character, we call <strong> <em>cin.ignore()</em> </strong> without any arguments. As a result, the <strong> <em>&apos;secondCharacter&apos;</em> </strong> variable only contains the <strong> <em>second character</em> </strong> .</p> <h3>Until a Delimiter</h3> <p>Let&apos;s say we simply want to <strong> <em>read</em> </strong> the first word from a user-provided line of text. We can accomplish this with the help of <strong> <em>cin.ignore()</em> </strong> and the delimiter specified as follows:</p> <pre> #include #include int main() { std::string firstWord; std::cout&lt;&gt;std::ws, firstWord, &apos; &apos;); std::cout&lt;&lt; &apos;The first word is: &apos; &lt;<firstword<<std::endl; return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> Enter a sentence: Hello, World! How are you? The first word is: Hello, </pre> <p> <strong>Explanation:</strong> </p> <p>In the above example, leading <strong> <em>whitespace</em> </strong> is skipped using <strong> <em>std::ws</em> </strong> before the input is read using <strong> <em>getline()</em> </strong> . When the <strong> <em>delimiter</em> </strong> is set to a <strong> <em>space (&apos; &apos;), cin.ignore()</em> </strong> will only extract the first word and disregard all other characters up to that point.</p> <h2>Conclusion:</h2> <p>For addressing input-related concerns and providing exact control over the input buffer, the C++ <strong> <em>cin.ignore() function</em> </strong> is a useful tool. Developers can efficiently handle undesired characters and accomplish the required behavior in their programs by understanding its syntax, usage, and functioning principle.</p> <p>Developers can ensure precise and anticipated input procedures by using the <strong> <em>cin.ignore() function</em> </strong> to skip until a designated delimiter or disregard a set of characters. When working with mixed input types, numeric input that is followed by string input, or when reading strings using <strong> <em>getline()</em> </strong> , this function is quite helpful.</p> <p>Developers can avoid unexpected behavior brought on by lingering characters in the input buffer by properly using <strong> <em>cin.ignore()</em> </strong> . By clearing the buffer and allowing for the reading of new input, this function aids in maintaining the integrity of following input operations.</p> <p>For proper handling of various input conditions, it is imperative to comprehend the parameters and behavior of <strong> <em>cin.ignore()</em> </strong> . With the help of <strong> <em>cin.ignore()</em> </strong> , programmers can create <strong> <em>powerful</em> </strong> and <strong> <em>dependable</em> </strong> input handling systems for their <strong> <em>C++ programs</em> </strong> , whether they want to ignore a single character or skip till a delimiter.</p> <p>In conclusion, the <strong> <em>cin.ignore() function</em> </strong> is a crucial part of C++ input processing since it enables programmers to remove unnecessary characters and guarantee accurate and seamless input operations. Understanding how to use it effectively can considerably improve the stability and usability of C++ applications.</p> <hr></firstword<<std::endl;></pre></secondcharacter<<std::endl;>

Пояснення:

У наведеному вище прикладі ми використовуємо std::noskipws до зупинити символи від читання з пропуском пробілів. Щоб прибрати небажаний символ після прочитання першого символу, викликаємо cin.ignore() без жодних аргументів. В результаті, 'secondCharacter' змінна містить лише другий символ .

До розділювача

Скажімо, ми просто хочемо читати перше слово з наданого користувачем рядка тексту. Ми можемо досягти цього за допомогою cin.ignore() і роздільник, визначений таким чином:

 #include #include int main() { std::string firstWord; std::cout&lt;&gt;std::ws, firstWord, &apos; &apos;); std::cout&lt;&lt; &apos;The first word is: &apos; &lt;<firstword<<std::endl; return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> Enter a sentence: Hello, World! How are you? The first word is: Hello, </pre> <p> <strong>Explanation:</strong> </p> <p>In the above example, leading <strong> <em>whitespace</em> </strong> is skipped using <strong> <em>std::ws</em> </strong> before the input is read using <strong> <em>getline()</em> </strong> . When the <strong> <em>delimiter</em> </strong> is set to a <strong> <em>space (&apos; &apos;), cin.ignore()</em> </strong> will only extract the first word and disregard all other characters up to that point.</p> <h2>Conclusion:</h2> <p>For addressing input-related concerns and providing exact control over the input buffer, the C++ <strong> <em>cin.ignore() function</em> </strong> is a useful tool. Developers can efficiently handle undesired characters and accomplish the required behavior in their programs by understanding its syntax, usage, and functioning principle.</p> <p>Developers can ensure precise and anticipated input procedures by using the <strong> <em>cin.ignore() function</em> </strong> to skip until a designated delimiter or disregard a set of characters. When working with mixed input types, numeric input that is followed by string input, or when reading strings using <strong> <em>getline()</em> </strong> , this function is quite helpful.</p> <p>Developers can avoid unexpected behavior brought on by lingering characters in the input buffer by properly using <strong> <em>cin.ignore()</em> </strong> . By clearing the buffer and allowing for the reading of new input, this function aids in maintaining the integrity of following input operations.</p> <p>For proper handling of various input conditions, it is imperative to comprehend the parameters and behavior of <strong> <em>cin.ignore()</em> </strong> . With the help of <strong> <em>cin.ignore()</em> </strong> , programmers can create <strong> <em>powerful</em> </strong> and <strong> <em>dependable</em> </strong> input handling systems for their <strong> <em>C++ programs</em> </strong> , whether they want to ignore a single character or skip till a delimiter.</p> <p>In conclusion, the <strong> <em>cin.ignore() function</em> </strong> is a crucial part of C++ input processing since it enables programmers to remove unnecessary characters and guarantee accurate and seamless input operations. Understanding how to use it effectively can considerably improve the stability and usability of C++ applications.</p> <hr></firstword<<std::endl;>

Пояснення:

У наведеному вище прикладі провідний пробіл пропускається за допомогою std::ws перед тим, як введення буде прочитано за допомогою getline() . Коли роздільник встановлено на a пробіл (' '), cin.ignore() вилучатиме лише перше слово та ігноруватиме всі інші символи до цього моменту.

висновок:

Для вирішення проблем, пов’язаних із введенням даних, і забезпечення точного контролю над буфером введення, C++ функція cin.ignore(). є корисним інструментом. Розробники можуть ефективно обробляти небажані символи та досягати необхідної поведінки у своїх програмах, розуміючи їх синтаксис, використання та принцип функціонування.

Розробники можуть забезпечити точні та передбачувані процедури введення за допомогою функція cin.ignore(). щоб пропустити до визначеного роздільника або ігнорувати набір символів. Під час роботи зі змішаними типами введення, числового введення, за яким слідує введення рядка, або під час читання рядків за допомогою getline() , ця функція дуже корисна.

Розробники можуть уникнути несподіваної поведінки, спричиненої затримкою символів у буфері введення, правильно використовуючи cin.ignore() . Очищаючи буфер і дозволяючи зчитувати новий вхід, ця функція допомагає підтримувати цілісність наступних операцій введення.

Для належного поводження з різними вхідними умовами необхідно розуміти параметри та поведінку cin.ignore() . За допомогою cin.ignore() , програмісти можуть створювати потужний і надійний системи обробки вхідних даних для їх Програми C++ , чи хочуть вони ігнорувати окремий символ чи пропускати до розділювача.

На закінчення, функція cin.ignore(). є важливою частиною обробки вхідних даних C++, оскільки вона дозволяє програмістам видаляти непотрібні символи та гарантувати точні та безперебійні операції введення. Розуміння того, як його ефективно використовувати, може значно покращити стабільність і зручність використання програм C++.