POV-Ray : Newsgroups : povray.off-topic : My first C++ program : Re: My first C++ program Server Time
4 Nov 2024 17:31:56 EST (-0500)
  Re: My first C++ program  
From: Warp
Date: 21 Sep 2008 07:21:26
Message: <48d62e33@news.povray.org>
Warp <war### [at] tagpovrayorg> wrote:
>   What you can do is this:

>     std::string s;
>     while(true)
>     {
>         std::cin >> s;
>         if(!std::cin.good()) break;

>         int value;
>         std::istringstream iss(s);
>         iss >> value;
>         if(!iss.fail())
>             std::cout << "The input was an integer: " << value << "\n";
>         else
>             std::cout << "The input was something else: " << s << "\n";
>     }

  Actually there is a way to achieve the same thing with std::cin
directly, without having to use stringstreams.

  If an input stream fails to read data which fits the parameter type,
it will stop reading, so anything that was in the input (which was not
whitespace) will be left there. It's thus possible to check if reading
the integer filed, and if it did, read it as a string.
  The only catch is that you have to clear the error flags of std::cin
before you can continue reading properly.

  The above example code can thus be written as:

    while(true)
    {
        int value;
        std::cin >> value; // Try to read an integer
        if(std::cin.fail()) // If there was no integer in the input
        {
            std::cin.clear(); // Clear the error flags
            std::string s;
            std::cin >> s; // Read a string
            if(!std::cin.good()) break;
            std::cout << "The input was something else: " << s << "\n";
        }
        else
        {
            std::cout << "The input was an integer: " << value << "\n";
        }
    }

  Thus removing the need for stringstreams.

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.