Re: Newbie string question: how to read off the first char from a string?
From: Victor Bazarov (v.Abazarov_at_comAcast.net)
Date: 02/28/05
- Next message: Victor Bazarov: "Re: sizeof(int)"
- Previous message: Jack Klein: "Re: Why we need classes"
- In reply to: Dylan Nicholson: "Re: Newbie string question: how to read off the first char from a string?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 27 Feb 2005 23:16:25 -0500
"Dylan Nicholson" <wizofaus@hotmail.com> wrote...
> "Victor Bazarov" <v.Abazarov@comAcast.net> wrote in message
> news:<nJ-dnZM-u8l3drzfRVn-oQ@comcast.com>...
>>
>> Second, unfortunately this is one of the serious omissions in the C++
>> streams, no setwidth or setprecision can help you read a field of any
>> *particular* width from a stream, so you have to use scanf for that or
>> resort to extracting fields into separate strings and reading them using
>> strtod or some such.
>>
>> If you doubt the statement above, I dare you to write code to extract
>> two 4-digit integers from the stream that contains '12345678' so that
>> the first one would be 1234 and the second 5678. Simple, isn't it? I
>> will even help you:
>>
>> #include <iostream>
>> #include <sstream>
>> #include <iomanip>
>> int main()
>> {
>> std::istringstream is("12345678");
>> int one, two;
>> ????
>
> char field[5] = "";
char field[5] = {}; // otherwise only the first one is guaranteed to be 0.
> is.read(field, 4);
> one = atoi(field); // may need extra header for this, or std::atoi
> is >> two;
IOW, there is no way to do it without the intervening string and additional
conversion sequence. Fixed-length fields are not easy to deal with in C++.
QED.
> [...]
- Next message: Victor Bazarov: "Re: sizeof(int)"
- Previous message: Jack Klein: "Re: Why we need classes"
- In reply to: Dylan Nicholson: "Re: Newbie string question: how to read off the first char from a string?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]