Total C noob needs to extract strings from string.

UtahJ
03-12-2004, 10:31 AM
Hello all... I'm a long time VB programmer who has been
thrown into a C program since I'm the only programmer left
at the company. :(

Anyway... The program is quite large, so I can't post all
of the code, but I have a string similar to "8x60" or "10x60".
I need to return either the 8 or the 10, and the 60.
I have successfully located the "x" using the following:

char str[] = "x";
int location;
char *pdest

fgets(s,7,ordfile_ptr);
pdest = strstr( s, str );
location = pdest - s + 1;

Again, this is only a fraction of the code I'm dealing with...
In VB I would use the Left, Right, and Mid funtions to extract
the "8", "10", or "60", based on the location of "x".

I have read that strings are treated as arrays in C. How
can I extract my information?

Thanks!

Sokolov
03-12-2004, 11:32 AM
Just a simple example to get you started.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
char line[] = "0x60";
int location;
char *ptr;

if((ptr = strchr(line, 'x')) != NULL)
{
ptr++;
if(isdigit(*ptr))
{
location = atoi(ptr);
printf("location = %d\n", location);
}
}
return 0;
}
Hope this helps.

Segosa
03-12-2004, 11:45 PM
char *s = "10x59";
char *first = new char[strlen(s)];
char *last = new char[16];
strcpy(first,s);
first[strchr(s,'x')-s] = 0;
last = strchr(s,'x')+1;
printf("first: %s last: %s",first,last);

UtahJ
03-15-2004, 02:33 PM
Thanks guys, this will get me headed in the
right direction. I'm sure I'll be asking more
questions as I start digging into the code
some more.

:D

UtahJ
03-19-2004, 10:09 AM
:huh:

I'm back....

For the most part everything works, but I hit a snag.
In the following code, spacer_rows is equal
to ""10" , and the wdg_rows[k] = atoi(spacer_rows);
line returns 0. I'm guessing this is because of the
double quotes at the beginning of the spacer_rows value.
I've spent two days looking for a way to get rid on the first
quote in spacer_rows. Very frustrating since I could do it in
15 seconds in VB. So.... how can I do it?

Again... this is only a fraction of the code....



char str[10],*spacer_rows=new char[10], *spacer_width=new char[10];

fgets(str,7,ordfile_ptr);

if (wdg_type[k] == 'S' || wdg_type[k] == 'D')
strcpy(spacer_rows,str);

spacer_rows[strchr(str,'x')-str] = 0;
spacer_width = strchr(str, 'x') + 1;
wdg_rows[k] = atoi(spacer_rows);
wdg_spcr_wdth[k] = atoi(spacer_width);

UtahJ
03-19-2004, 02:30 PM
No need to repond.... I found a work around. :-\

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum