logo

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

В C++, cin.ignore() функция е от съществено значение за разрешаването проблеми, свързани с въвеждането , особено при използване на храня се и функции на getline заедно. Чрез изчистване на входния буфер и премахване на ненужните знаци, разработчиците могат да гарантират, че процесите на въвеждане се държат според очакванията и точно. В тази статия ще разгледаме функциите на cin.ignore(). синтаксис, използване, примери , и очаквани резултати .

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

cin.ignore(n, разделител);

Параметри на функцията Cin.ignore() Синтаксис:

n (по избор): Показва колко знака трябва да бъдат игнориран .

Разделител (по избор): Той уточнява a разделителен знак , след което въведеното ще бъде пренебрегнато. Ако не посочени , по подразбиране е 1 . Ако нищо не е посочени , тогава знак за ewline ('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() и разделителят, определен както следва:

python записва json във файл
 #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++ приложенията.