[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How do I convert and validate numeric data to a string object?
From: |
Thomas Maeder |
Subject: |
Re: How do I convert and validate numeric data to a string object? |
Date: |
Wed, 13 Feb 2008 20:26:48 +0100 |
User-agent: |
Gnus/5.1006 (Gnus v5.10.6) XEmacs/21.4 (Jumbo Shrimp, linux) |
Pep <pepaltavista@yahoo.co.uk> writes:
> I have numeric input which I must convert to strings and validate
> whilst doing the conversion. I do not want to mix C functions like
> strtol in to my c++ code, so I'm trying to implement a C++ method
> using examples found in google but none of them work :(
std::strtol() is a Standard C++ function. Where's the problem?
> I have this test program to show my misunderstanding of what is going
> on. It also tests a second problem where I am trying to reset a
> istringstream but need to call the clear() member after the reset,
> which as I misunderstand things is not supposed to be required.
>
> #include <sstream>
> #include <iostream>
>
> long testLong;
> std::string testString;
>
> std::istringstream iss;
>
> iss.exceptions(std::istringstream::eofbit |
> std::istringstream::failbit | std::istringstream::badbit);
This doesn't compile (such a statement is only possible inside a
function definition).
Please post
- real, minimal code (just as much as needed, not more nor less)
- the input you are passing your program
- the output you get
- the output you expect (or hope for)
>
> iss.str(argv[1]);
>
> try
> // supposedly this will throw exception if conversion is non-
> numeric
> {
> iss >> testLong;
Side note: This overload of operator>> is declared in the header
<istream>, which you haven't included ...
> }
> catch(std::istringstream::failure& e)
> {
> std::cout << "caught a exception geezer! [" << e.what() << "]" <<
> std::endl;
... nor <ostream>, where std::endl and this overload of operator<< are
declared.
> So it appears that none of the methods used are capable of doing what
> I require, even though there are hundreds of entries in google that
> state this is the way to do?
>
> What are the "caught a exception geezer! [basic_ios::clear]"
> exceptions about?
They are a big strange; but I am not surprised that the eofbit is set
when parsing an integral number at the end of input.
> So how can I do what I want to do, which is simply to convert and
> validate a numeric input value to a string value?
The code you posted seems to convert from string to numeric, though.