Pages

C. average from string problem with strtok.

samedi 16 juillet 2016

Hi everyone i'm practicing with C, this program takes numbers in input but in string and divided with commas ("1,2,3,4") and the output is the average of the numbers. I don't know where I go wrong but it gives me always segmentation fault, can anybody help me?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

float* separa(char* string){

int dim=0;
int i=0;
float numero;

char* sep = "," ;
char* tokena;
char* token;
char* stringa;
strcpy (stringa, string);

for(token=strtok(stringa,sep); token!=NULL; token=strtok(NULL,sep))
{
dim++;
}

float *vet = (float*)malloc (dim*sizeof(float));

for(tokena=strtok(string,sep); tokena!=NULL; tokena=strtok(NULL,sep))
{
numero=atof(tokena);
vet[i]=numero;
i++;
}

return vet;
}

float media(char* stringa){

int i;
int dim=0;
char* token;
char* sep = ",";
float sum=0;
float risultato=0;
char* stringas;
strcpy/

for(token=strtok(stringas,sep); token!=NULL; token=strtok(NULL,sep))
{
dim++;
}

float* vettore = separa(stringa);
for(i=0;i<dim;i++){

sum = sum + vettore[i];
}

risultato = (sum/dim);

return risultato;

}

int main()
{
char* prova="3,2,1";
float a;
a=media(prova);
printf("%f\n", a);
return 0;
}

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at http://ift.tt/jcXqJW.
Recommended article from FiveFilters.org: Most Labour MPs in the UK Are Revolting.



C. average from string problem with strtok.

Aucun commentaire:

Enregistrer un commentaire