Re: [C++] Help Parsing an Integer/Character Mix
From: Francis Glassborow (francis_at_robinton.demon.co.uk)
Date: 02/21/04
- Previous message: less sexy: "How stupid is mktime() tm_mon"
- In reply to: entropy123: "[C++] Help Parsing an Integer/Character Mix"
- Next in thread: Guy Harrison: "Re: [C++] Help Parsing an Integer/Character Mix"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 20 Feb 2004 23:45:11 +0000
In message <90cdce37.0402201257.700aa672@posting.google.com>, entropy123
<email_entropy123@yahoo.com> writes
>This question goes to the heart of my troubles with C++, input gives
>me fits. I've scoured the nets and several books to no avail. Any
>strategies, advice much appreciated!
>
>I have this text file.
>
>It reads:
>
>2 A0032 B0054 3 B3203
>
>What I need to do is fill my datastructure like this:
>
>2 A0032
>1 B0054
>3 B3203
>
>
>My program isn't much yet, I tried using 'Peek()' to determine if the
>first line read in was an integer or not...but 'Peek()' returns an int
>value, I'm not sure how this helps me decide that B0054 does not have
>any integer in front of it...
One way to achieve your objective is to attempt to read an integer. If
it fails (i.e. the next bit of data does not start with an int your
input stream will fail. You can then reset it, do whatever you want to
do to supply the missing number then go one and read in the data as a
string. The following gives a possible solution:
int next_number(std::istream & in){
static int nextval(0);
int value;
in >> value;
if(!in) value = nextval;
nextval = value + 1;
in.clear(); // reset in to a good state
return value;
}
struct datapair {
int number;
std::string code;
};
datapair get_data(std::istream & in){
datapair dp = {0, ""};
dp.number = next_number(in);
in >> dp.code;
return dp;
}
And, yes, the above code could do with a good deal more work but should
set you in roughly the right direction.
-- Francis Glassborow ACCU Author of 'You Can Do It!' see http://www.spellen.org/youcandoit For project ideas and contributions: http://www.spellen.org/youcandoit/projects
- Previous message: less sexy: "How stupid is mktime() tm_mon"
- In reply to: entropy123: "[C++] Help Parsing an Integer/Character Mix"
- Next in thread: Guy Harrison: "Re: [C++] Help Parsing an Integer/Character Mix"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|