Home >Backend Development >C++ >How to Reliably Input Numbers Using `cin` in C ?

How to Reliably Input Numbers Using `cin` in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 16:22:10301browse

How to Reliably Input Numbers Using `cin` in C  ?

Troubleshooting Number Input with cin

In C , the cin function can be used to read user input, but it becomes problematic when attempting to validate the input as a valid number. This issue arises when non-numeric characters are input, potentially leaving behind partial input for the next iteration.

One solution is to utilize std::getline and std::string to read the entire line of input. Subsequently, std::stringstream is employed to parse the input and extract a double value. The loop continues until the entire line can be successfully converted to a double, eliminating the issue of leftover input.

#include <string>
#include <sstream>

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;
}

The above is the detailed content of How to Reliably Input Numbers Using `cin` 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