Home >Backend Development >C++ >How to Make `cin` Accept Only Numerical Input in C ?

How to Make `cin` Accept Only Numerical Input in C ?

DDD
DDDOriginal
2024-12-17 07:34:25619browse

How to Make `cin` Accept Only Numerical Input in C  ?

Making cin Read Only Numbers

Enforcing numerical input using cin can present challenges, especially when handling mixed input types. This article investigates a solution to ensure that cin accepts only numerical values.

In the provided code, while loops attempt to rectify invalid input by disregarding non-numerical characters. However, this method faces limitations when dealing with multiple inputs.

Solution: Using std::getline and std::string

To overcome this hurdle, we can employ a more comprehensive approach:

  1. Read the entire line using std::getline(): This reads the complete line of user input as a string.
  2. Convert the string to a double using std::stringstream:

    • Create a stringstream ss from the input line.
    • Attempt to extract a double using the >> operator.
  3. Validate the conversion:

    • Check if the conversion is successful and if the stream has reached the end of the string (eof()).
    • If successful, exit the loop. Otherwise, display an error message.

Here's an example implementation:

#include <sstream>
#include <string>

int main()
{
    std::string line;
    double d;
    while (std::getline(std::cin, line))
    {
        std::stringstream ss(line);
        if (ss >> d)
        {
            if (ss.eof())
            {   // Success
                break;
            }
        }
        std::cout << "Error!" << std::endl;
    }
    std::cout << "Finally: " << d << std::endl;
}

This solution ensures that both integers and floating-point numbers are processed correctly, with non-numerical characters being discarded completely.

The above is the detailed content of How to Make `cin` Accept Only Numerical Input in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn