Re: Test a string for Integer
On 14 Nov., 23:20, kingbarsa <barry.kingw...@gmail.com> wrote:
If you are reading a string from an external file, and want to check
whether that string contains a single integer or a string of text. how
to?
Eg
fgets(tmpstr,80,disk);
char szBuffer[2];
StrLCopy(szBuffer,tmpstr,1);
AnsiString tempstr = szBuffer;
if (tempstr.ToInt()............
This code does not use much components of the standard C++ library.
E.g. names like StrLCopy, AnsiString have no meaning for the
the general reader of this group.
I don't want it to throw an Convert Exception if it is not an Integer,
I still want to proceed and use the text string in tmpstr, OR if it is
an integer then use that integer and assign it to a variable.
What check do I use, to test if the line starts with an integer or
not?
In non-portable mode, I would suggest the function TryStrToInt
from SysUtils if you are using one of the Borland compilers.
To make this question more interesting for the general
reader of this group: You could use a string stream,
assign the string to it and attempt to extract an int
value:
#include <string>
#include <sstream>
bool try_read(const std::string& s, int& val) {
std::istringstream buf(s);
return (buf >> val);
}
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]