Sign in to follow this  
cnjcombo

Trouble converting string to int and strcat

Recommended Posts

With the code I have supplied below I am trying to run through a string array and break apart the integers that are seperated by commas ( i.e. 25000,3000,32500,4800 would be broken down into 4 different strings and then converted to ints). The converting to int's and concatenating the strings seems to be the problem and I cannot figure it out. The program compiles and builds but crashes and doesn't even print out the first "heresofar1". Below are the warnings that Visual Studio gives me.... Ugh, I need help... If anyone knows an easier way to do this as well I am all ears. -------------------Configuration: arrow - Win32 Debug-------------------- Compiling... prim.c C:\Documents and Settings\CJ\Desktop\prim.c(78) : warning C4047: 'function' : 'const char *' differs in levels of indirection from 'char ' C:\Documents and Settings\CJ\Desktop\prim.c(78) : warning C4024: 'strcat' : different types for formal and actual parameter 2 prim.obj - 0 error(s), 2 warning(s)
	FILE *f;
    char s[1000];		
	int i;	
	int comma_count;
	char *fnames[6] = { "div105.txt", "div205.txt",
		"div305.txt", "div104.txt", "div204.txt", "div304.txt"};
	char temp;	
	char temp1[6];
	// read-in from file
	f=fopen(fnames[0],"r");
    if (!f)
	{printf("wammy",s);}
    while (fgets(s,1000,f)!=NULL)
	{		
	}
    fclose(f);// close file buffer

	comma_count = 0;	
	printf("%s", s);
	for (i = 0; s[i] != '\0'; i++)
    {		
		if ( s[i] == ',' )
		{
			printf("heresofar2");
			divpct05[0][comma_count] = atoi(temp1);
			comma_count++;
		}else
		{
			if ( comma_count == 0 )
			{
				temp = s[i];
				strcat( temp1, temp );				
				printf("heresofar1");
				//printf("%divpct05[0][0]",divpct05[0][0]);
			}else if ( comma_count == 1)
			{
				//strcat( divpct05[0][1], s[i] );				
			}else if (comma_count == 2)
			{
				//strcat( divpct05[0][2], s[i] );				
			}else if (comma_count == 3)
			{
				//strcat( divpct05[0][3], s[i] );				
			}
		}


Share this post


Link to post
Share on other sites
sory but i find your code difficult to read.

ill point at a few things maybe.

the code:

if (!f)
{printf("wammy",s);}

what is it supposed to do

s is an unitialised string and should be outputted with print("wammy%s",s);

and here

strcat( temp1, temp );

temp is a character, not a string. strcat takes two strings as arguments

i can only assume divpct05 is some global / predefined variable...

and here
while (fgets(s,1000,f)!=NULL)
{
}
my memory of the c functions is hazy, but wont this contniue to overwrite the data present in s until the end of the file.

and this

if ( comma_count == 0 )
{
temp = s[i];
strcat( temp1, temp );
printf("heresofar1");
//printf("%divpct05[0][0]",divpct05[0][0]);
}else if ( comma_count == 1)
{
//strcat( divpct05[0][1], s[i] );
}else if (comma_count == 2)
{
//strcat( divpct05[0][2], s[i] );
}else if (comma_count == 3)
{
//strcat( divpct05[0][3], s[i] );

}



assumes a maximum of 3 commas

use strcat( divpct05[0][comma_count], somestringvar[i] );

and also i skipped bits

break your code into logical functions

1 read the data from a file;
2 seperate the data into individual strings
3 get the integer values of those strings

Share this post


Link to post
Share on other sites
I have now cleaned up my code and gotten it so that it does not crash( as well as fully commented). Now I am getting output like the following, I do not know why because chars are being passed to char arrays so I do not know why the funky output:

Contents of temp1: 2╠╠╠╠╠╠╠2╠╠╠ö`B Contents of temp1: 2╠╠╠╠╠╠╠5╠╠╠ö`B5x`B Conten
ts of temp1: 2╠╠╠╠╠╠╠0╠╠╠ö`B5x`B0h`B Contents of temp1: 2╠╠╠╠╠╠╠0╠╠╠ö`B5x`B0h`B0
X`B Contents of temp1: 2╠╠╠╠╠╠╠0╠╠╠ö`B5x`B0h`B0X`B0↑qB


FILE *f;
char s[100];
int i,j;
int comma_count;
char *fnames[6] = { "div105.txt", "div205.txt",
"div305.txt", "div104.txt", "div204.txt", "div304.txt"};
char temp[1];
char temp1[6];
// read-in from file
f=fopen(fnames[0],"r");
if (!f)
{printf("wammy",s);}
while (fgets(s,1000,f)!=NULL)
{
}
fclose(f);// close file buffer

comma_count = 0;// initialize comma_count to 0
printf("%s", s);// print contents of s to check that data was read-in successfully
temp1[0] = '\0';// initialize temp1[0] as null
temp[0] = '\0';// initialize temp1[0] as null
j = 0;
// loop thru s char array to sort integers
for (i = 0; s[i] != '\0'; i++)
{
if ( s[i] == ',' )// if current char is a comma
{
// converts temp1 string into int and sets divpct array to that value
divpct05[0][comma_count] = atoi(temp1);
comma_count++;// inc comma_count
}else
{
if ( comma_count == 0 )// if no commas hit yet
{
temp[0] = s[i];//temp[0] is equal to char at s[i]
while( temp1[j] != '\0' )// checking for first empty rank of temp1
{
j++;
}
temp1[j] = s[i];// first empty rank of temp1 is changed to value of s[i]
printf("Contents of temp1: %s ", temp1);//check for method progress
}
if ( comma_count == 1)
{

}
if (comma_count == 2)
{

}
if (comma_count == 3)
{

}
}

}



Share this post


Link to post
Share on other sites

#include <stdio.h>

int main( int argc, char**argv )
{
FILE *file = fopen("data.txt","r" );
if( file == NULL ){
printf("error opening file");
return 0;
}
int commas = 1;// one more because ...
while( !feof( file ) ){ // quick comma count
if( fgetc( file ) == ',' )
++commas; // you could put some
}// error checking in here
// in case of not ints/commas in file
rewind( file ); // go back to start
if( commas > 1000 ){
fclose( file );
printf("too many integers");
return 0;
}
int result[1000];
for( int i = 0 ; i < commas - 1 ; ++i ){
fscanf(file,"%d,",result+i ); // read in the result
} // the "%d," is not a typo
fscanf(file,"%d", result+commas-1);
fclose( file );
for( int i = 0 ; i < commas ; ++i )
printf("result[%d] == %d\n",i,result[i]);
return 0;
}




its fun having free periods in college...

get to write crappy programs instead of working

btw, your code is a bit all over the place.

things like unhelpful variable names and unused variables make baby jebus cry

Share this post


Link to post
Share on other sites
heh, i apologize for the variable names, have tried a million different approaches to what i am trying to do and when switching variable types so many times i just went with temp, should have cleaned it up since i was posting on a forum for help.

Quote:

its fun having free periods in college...

get to write crappy programs instead of working


it wouldnt be so bad if they didnt preach Java so much and then tell us all of our prgms have to be written strictly in C for a course.

Any ideas on a better approach to deciphering int's from a string?

Share this post


Link to post
Share on other sites
Devide and conquer is good


int getints(char* stri, int[] res, int& n, int resmaxsize)
{
int i=0,wc=0,l=strlen(stri);
char[30] word; //I doubt an integer will be more than 30 chars long
word[0]='\0';
n=0;
while (i<=l) {
if ((i==l) || (stri[i]==',')) {
word[wc]='\0';
wc=0;
n++;
if (n>resmaxsize) return 0;
res[n-1]=atoi(word);
} else if (wc<28) { //this prevents to go outside the bounds of the char array
word[wc]=stri[i];
wc++;
}
i++;
}


return 1;

}



Should take stri (the string), res an int array, n variable that will have the total number of found ints, and resmaxsize is the maximum number of ints that should be there.

If there is an overflow it returns 0 otherwise it returns 1.

You might want to make it use bool as return type and return true and false instead of 1 and 0, it is up to you. Something there might be wrong, didn't have access to a compiler right now

[Edited by - Vexorian on October 7, 2005 6:44:25 PM]

Share this post


Link to post
Share on other sites
your main problem is the layout of the string

lets assume you read it in one big lump

so in memory we have:

(using -> notation to say points to, not the pointer_to_struct_member operator)

char *data -> "1","2","3",",","4","5","6",",","7" ...
// note the commas inthe string

you can do this:

search the string for a ','.

when you find said comma turn it into the NUL char '\0' and store a pointer to the start of the next..

so then you have

char *array[SOME_NUM];

array[0]-> "1","2","3","\0" array[1]->"4","5","6","\0" array[2] -> "7" ...

at the end you do:

int array_of_ints[SOME_NUM];

for( int i = 0 ; i < num_ints ; ++i )// num_ints should be num_commas + 1
array_of_ints[i] = atoi( array[i] );

hope this helps

[Edited by - rip-off on October 8, 2005 8:17:08 AM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this