Re: Type of elements of std::string
On Jan 26, 2:52 pm, Jerry Coffin <jerryvcof...@yahoo.com> wrote:
In article <Pine.GHP.4.64.1001251045190.17...@kinga.cyf-kr.edu.pl>,
nbbie...@cyf-kr.edu.pl says...
What is actually the type of elements of std::string?
char. Specifically, the definition of std::string looks like:
typedef basic_string<char> string;
I am trying to read the elements from a stream, in the following
way:
std::string str = "";
int c;
// Read string size
int n;
is >> n;
// Read string
for(int i=0; i<n; i++)
{
c = is.get();
str += c;
}
Hmm...I think I'd do this more like:
int n;
is >> n;
std::string str(n, ' ');
is.read(&str[0], n);
This should eliminate the warning(s), and if there's a
difference in efficiency, I'd guess it's more likely to favor
this version than the other. In theory, this isn't entirely
portable -- the current standard doesn't guarantee that
std::string will use contiguous storage for the characters. In
reality, current implementations do use contiguous storage,
and the next version of the standard will require it, so
there's not really much chance of a new implementation that
uses non-contiguous storage.
What happens if there aren't n characters left to read? (And in
fact, I don't know. I practically never use istream::read, and
I don't have any documentation handy to check. But it's
obviously a case which has to be considered.)
More generally, considering the first algorithm: the
no-argument form of istream::get returns an int in order to
return out of band data, e.g. EOF. Once that data has been
tested for and excluded, the resulting value must be converted
to a char. Formally, a rather complex operation, since the
resulting value is in the range 0...UCHAR_MAX, which might not
fit into a char (and if the results don't fit, the behavior is
implementation defined, and might result in a signal).
Practically, implementations which use signed plain char will
always ensure that this works, given that it is such a standard
idiom (in C, at least). But if you really want to avoid it,
something like:
char ch;
// ...
if ( input.get( ch ) ) {
// succeeded, you can safely use ch...
} else {
// error or end of file, the contents of
// ch are unchanged.
}
--
James Kanze