Trouble converting string to int and strcat

Started by
6 comments, last by rip-off 18 years, 6 months ago
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 != '\0'; i++)
    {		
		if ( s == ',' )
		{
			printf("heresofar2");
			divpct05[0][comma_count] = atoi(temp1);
			comma_count++;
		}else
		{
			if ( comma_count == 0 )
			{
				temp = s;
				strcat( temp1, temp );				
				printf("heresofar1");
				//printf("%divpct05[0][0]",divpct05[0][0]);
			}else if ( comma_count == 1)
			{
				//strcat( divpct05[0][1], s );				
			}else if (comma_count == 2)
			{
				//strcat( divpct05[0][2], s );				
			}else if (comma_count == 3)
			{
				//strcat( divpct05[0][3], s );				
			}
		}


Advertisement
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;				strcat( temp1, temp );								printf("heresofar1");				//printf("%divpct05[0][0]",divpct05[0][0]);			}else if ( comma_count == 1)			{				//strcat( divpct05[0][1], s );							}else if (comma_count == 2)			{				//strcat( divpct05[0][2], s );							}else if (comma_count == 3)			{				//strcat( divpct05[0][3], s );						}

assumes a maximum of 3 commas

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

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
That is what I am trying to do, divpct05[0][0] is one of a few multidimensional arrays used to store each integer. I will work with my code a little more and post
my results....
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 != '\0'; i++)    {				if ( s == ',' )// 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;//temp[0] is equal to char at s				while( temp1[j] != '\0' )// checking for first empty rank of temp1				{					j++;				}				temp1[j] = s;// first empty rank of temp1 is changed to value of s				printf("Contents of temp1: %s ", temp1);//check for method progress							}			if ( comma_count == 1)			{							}			if (comma_count == 2)			{							}			if (comma_count == 3)			{							}		}    }


#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);	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
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?
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==',')) {             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;             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]
------ XYE - A new edition of the classic Kye
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 = atoi( array );

hope this helps

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

This topic is closed to new replies.

Advertisement