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

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

Linda Hamilton
Release: 2024-12-16 16:22:10
Original
290 people have browsed it

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template