Перейти к содержимому

Cin fail c что это

  • автор:

Cin fail c что это

I don’t really understand the usage of cin.fail()

I’m not really sure what I want to ask here. So if I run this program it will repeat cin >> number until I enter a non-int. But then it prints the last int value I gave it. Does it not overwrite the value of number if it isn’t the correct type?

Well how about if I do this (Take away the ! in line 11).

So then it should repeat until it gets an int. But. it goes into an infinite loop of displaying «Not a number». How come it doesn’t do line 8 cin >> number; ? I also tried putting a cin >> number outside of the loop and it still just skips over it.

And the example where I seen this used it like this.

I see that this works, but what if I don’t want it to stop once I enter something that isn’t the right type?

23.5 — Stream states and input validation

The ios_base class contains several state flags that are used to signal various conditions that may occur when using streams:

Although these flags live in ios_base, because ios is derived from ios_base and ios takes less typing than ios_base, they are generally accessed through ios (e.g. as std::ios::failbit).

ios also provides a number of member functions in order to conveniently access these states:

The most commonly dealt with bit is the failbit, which is set when the user enters invalid input. For example, consider the following program:

Note that this program is expecting the user to enter an integer. However, if the user enters non-numeric data, such as “Alex”, cin will be unable to extract anything to age, and the failbit will be set.

If an error occurs and a stream is set to anything other than goodbit, further stream operations on that stream will be ignored. This condition can be cleared by calling the clear() function.

Input validation is the process of checking whether the user input meets some set of criteria. Input validation can generally be broken down into two types: string and numeric.

With string validation, we accept all user input as a string, and then accept or reject that string depending on whether it is formatted appropriately. For example, if we ask the user to enter a telephone number, we may want to ensure the data they enter has ten digits. In most languages (especially scripting languages like Perl and PHP), this is done via regular expressions. The C++ standard library has a regular expression library as well. Because regular expressions are slow compared to manual string validation, they should only be used if performance (compile-time and run-time) is of no concern or manual validation is too cumbersome.

With numerical validation, we are typically concerned with making sure the number the user enters is within a particular range (e.g. between 0 and 20). However, unlike with string validation, it’s possible for the user to enter things that aren’t numbers at all — and we need to handle these cases too.

To help us out, C++ provides a number of useful functions that we can use to determine whether specific characters are numbers or letters. The following functions live in the cctype header:

Let’s do a simple case of string validation by asking the user to enter their name. Our validation criteria will be that the user enters only alphabetic characters or spaces. If anything else is encountered, the input will be rejected.

When it comes to variable length inputs, the best way to validate strings (besides using a regular expression library) is to step through each character of the string and ensure it meets the validation criteria. That’s exactly what we’ll do here, or better, that’s what std::all_of does for us.

Note that this code isn’t perfect: the user could say their name was “asf w jweo s di we ao” or some other bit of gibberish, or even worse, just a bunch of spaces. We could address this somewhat by refining our validation criteria to only accept strings that contain at least one character and at most one space.

Reader “Waldo” provides a C++20 solution (using std::ranges) that addresses these shortcomings here

Now let’s take a look at another example where we are going to ask the user to enter their phone number. Unlike a user’s name, which is variable-length and where the validation criteria are the same for every character, a phone number is a fixed length but the validation criteria differ depending on the position of the character. Consequently, we are going to take a different approach to validating our phone number input. In this case, we’re going to write a function that will check the user’s input against a predetermined template to see whether it matches. The template will work as follows:

A # will match any digit in the user input.
A @ will match any alphabetic character in the user input.
A _ will match any whitespace.
A ? will match anything.
Otherwise, the characters in the user input and the template must match exactly.

So, if we ask the function to match the template “(###) ###-####”, that means we expect the user to enter a ‘(‘ character, three numbers, a ‘)’ character, a space, three numbers, a dash, and four more numbers. If any of these things doesn’t match, the input will be rejected.

Here is the code:

Using this function, we can force the user to match our specific format exactly. However, this function is still subject to several constraints: if #, @, _, and ? are valid characters in the user input, this function won’t work, because those symbols have been given special meanings. Also, unlike with regular expressions, there is no template symbol that means “a variable number of characters can be entered”. Thus, such a template could not be used to ensure the user enters two words separated by a whitespace, because it can not handle the fact that the words are of variable lengths. For such problems, the non-template approach is generally more appropriate.

When dealing with numeric input, the obvious way to proceed is to use the extraction operator to extract input to a numeric type. By checking the failbit, we can then tell whether the user entered a number or not.

Let’s try this approach:

If the user enters an integer, the extraction will succeed. std::cin.fail() will evaluate to false, skipping the conditional, and (assuming the user entered a positive number), we will hit the break statement, exiting the loop.

If the user instead enters input starting with a letter, the extraction will fail. std::cin.fail() will evaluate to true, and we will go into the conditional. At the end of the conditional block, we will hit the continue statement, which will jump back to the top of the while loop, and the user will be asked to enter input again.

  1. If you want this to be valid input, you now have garbage in your stream.
  2. If you don’t want this to be valid input, it is not rejected (and you have garbage in your stream).

Let’s fix the first problem. This is easy:

If you don’t want such input to be valid, we’ll have to do a little extra work. Fortunately, the previous solution gets us half way there. We can use the gcount() function to determine how many characters were ignored. If our input was valid, gcount() should return 1 (the newline character that was discarded). If it returns more than 1, the user entered something that wasn’t extracted properly, and we should ask them for new input. Here’s an example of this:

Numeric validation as a string

The above example was quite a bit of work simply to get a simple value! Another way to process numeric input is to read it in as a string, then try to convert it to a numeric type. The following program makes use of that methodology:

Whether this approach is more or less work than straight numeric extraction depends on your validation parameters and restrictions.

cin.ignore; cin.clear; cin.fail

Потоковые обьекты, такие как cin и cout , также как и любой другой обьект, имеют определенное состояние. Для них состояние оценивается установкой определенных бит, goodbit (установлен по умолчанию и имеет нулевое значение), badbit, failbit . Если по какой то причине поток «сломался», то установится badbit , и программа аварийно завершится. Если была попытка чтения типа, но невозможно читать его из буфера, то устанавливается состояние failbit .

  1. std::cin.fail() будет означать: да, установлен failbit , поэтому любая попытка читать дальше, будет безуспешным. std::cin будет ждать очистки всех установленных битов состояния.
  2. Это делается функцией std::cin.clear , вызов которого приводит к обнулению всех битов состояния, а это и есть goodbit . Только после этого можем попытаться читать что то другое. Если мы решили, что в таком случаи(раз не было там числа) нужно пропустить строку и попытаться читать число в новой строке, то мы даем команду «игнорировать»(читать, но оставлять в буфере) много символов, пока не встретим символ перевода строки.
  3. std::cin.ignore(32767,’\n’); и есть эта команда(вместо 32767 может быть любая большая цифра такая, что точно больше, чем количество символов до ‘\n’)

AR Hovsepyan's user avatar

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.8.2.43556

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Cin fail c что это

Ensure that you are logged in and have the required permissions to access the test.

A server error has occurred. Please refresh the page or try after some time.

An error has occurred. Please refresh the page or try after some time.

We care about your data privacy. HackerEarth uses the information that you provide to contact you about relevant content, products, and services.

Our Privacy Policy and Terms of Service will help you understand that you are in control of your data at HackerEarth.

Signup and get free access to 100+ Tutorials and Practice Problems Start Now

Inputs have to be validated before allowing any kind of processing or operations to be performed on it. This is extremely important because , an unhandled wrong input might have the complete ability to crash a system. C++ has some good validation techniques that can be used to validate most kind of inputs. This post discusses some of the techniques and its shortcomings and what could be done to improve the quality of validation.

Now, consider a program has to accept only integer inputs and reject all the others. So, the developer would have declared to store the integer value in say “int a;”. So “a” will store the input value.

When the user input is accepted using the “cin>>a” statement, we can use the inbuilt methods surrounding the “cin” statement to test its status.

Here is a sample program: —

From the above example, the various functions are used to validate the input like the cin.fail(), cin.ignore(), etc. The various functions of these methods are :

cin.fail() — This function returns true when an input failure occurs. In this case it would be an input that is not an integer. If the cin fails then the input buffer is kept in an error state. cin.clear() — This is used to clear the error state of the buffer so that further processing of input can take place. This ensures that the input does not lead to an infinite loop of error message display. cin.ignore() — This function is used to ignore the rest of the line after the first instance of error that has occurred and it skips to or moves to the next line. cin.eof() — This function can be used to check end of file errors. This returns 1 if the program tried reading something but , it was from the end of the file.

Here is a screenshot of the various wrong inputs given, and them being handled by the program till a correct input is provided.

imput valid

Though this technique seems to work fine it hides a dangerous fault that can occur. This can be considered as a dis advantage of using c++. This technique does not catch certain types of input. The following screenshots show 2 inputs that is accepted and the numerical part is printed.

invalid1

invalid2

So, how can this erroneous inputs be handled? The technique we can apply is to accept the input as a string. The analyse the string to be of the illegal types shown above using regular expressions. If the input is valid then convert it into an integer and use it in the program else display an error message. Though its possible, its very difficult to be achieved in c++. This is mainly because , c++ doesn’t support regular expressions by default, we have to make use of the regex library which is quite complex to use. So to conclude, though C++ provides some handy tools to validate inputs, it does not help us to cover all possible situations in a straight forward way, which would lead us to use other workarounds to get our job done. But the validation of input can be handled in an efficient way with languages like java and c#.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *