| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | C |
On May 28, 1994 at 08:17, Bob Lawrence of 3:711/934.12 wrote:
BL> How the bloody hell do I read part of a string in C? I've got
BL> 3:711/934.12 and I want to read the 711. How do I do it? In Pascal I'd
BL> use COPY("3:711/934.12",3,3); but how do you pick a string out of a
BL> string in C?
Ahh .. "substring extraction" (doncha just luv dat jargon?).
Setup:
char *addrstr = "3:711/934.12";
int zone, net, node, point;
Execution:
sscanf( addrstr, "%d:%d/%d.%d", &zone, &net,
&node, &point );
Result:
zone Contains the zone number (as an integer).
net Contains the net number (as an integer).
node Contains the node number (as an integer).
point Contains the point number (as an integer).
That's of course, assuming you want to extract each part of the address
string into useable numbers. If you're interested in a "generic"
string extraction method, how about:
sscanf( source_string, "%*2s%3s", destination_string );
Read the format string like this:
%*2s Read in a string (%s) of at most, 2 characters, then
discard them (*).
%3s Read in a string (%s) of at most, 3 characters.
As I said when you were over here last time - the scanf() family of
functions (scanf, sscanf, fscanf..) is one mighty powerful set of tools,
and take a while to master.
I must admit, the first thing I did is go looking through the str..() set
of functions, but upon finding nothing directly useful there, I turned to
the fallback method - sscanf() (ie., perform scanf on a string). Worked
like a charm (yes, I tested them here a few minutes ago).
BL> I should explain that I haven't used Pascal for five years, and it
BL> took me two minutes to find the right command. I've been arsing around
BL> with C all day! And no closer than when I started.
That's okay .. you just weren't used to the available function set, that's
all. I'll let you in on a secret (!) - since C "strings" are
just pointers to arrays of characters, you can point straight to the third
character (element number 2 in the character array, counting from zero),
and only work with the first three characters that you find there.
In C, there's always more than one way to skin the cat.
BL> Is there any way, other than using a loop and building a new string
BL> character by character? I can't believe it's that clumsy. Help!
As above - is one function call a better method? :-)
- dave
david{at}zeppo.nepean.uws.edu.au
---
* Origin: [ epicentre of the universe -- sydney australia ] (3:711/934.4)SEEN-BY: 711/934 @PATH: 711/934 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.