Saludos, necesito separar una cadena "a,b,,d" y luego imprimir 0 donde no haya datos.
a
b
0
d
Alguna idea?, si uso strok, el no imprime campos vacíos.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int split(float *res , char *string , char delim);
int split(float *res , char *string , char delim){
int strLen = 0;
int commaCount =0; // count the number of commas
int commaCountOld =0; // count the number of commas
int wordEndChar = 0;
int wordStartChar = -1;
int wordLength =0;
for(strLen=0; string[strLen] != '\0'; strLen++){ // first get the string length
if ( (string[strLen] == delim) || ( string[strLen+1] == '\0' )) {
commaCount++;
wordEndChar = strLen;
}
if ( (commaCount - commaCountOld) > 0 ) {
int aIter =0;
wordLength = (wordEndChar - wordStartChar);
char word[55] = "";
for (aIter = 0; aIter < wordLength; aIter++) {
word[aIter] = string[strLen-wordLength+aIter+1];
}
if (word[aIter-1] == delim) word[aIter-1] = '\0';
// printf("\n");
word[wordLength] = '\0';
res
[commaCount
-1] = atof(&word
[0]); wordLength = 0;
wordStartChar = wordEndChar;
commaCountOld = commaCount;
}
}
return commaCount;
}
void main(){
char string[] = "1,,3"; // specify input here
float array_r[10]; // specify size of float array here
int totalValues = 0;
char myDelim = ','; // specify delimiter here
printf("string => %s \n",&string
[0]); totalValues = split(&array_r[0] , &string[0], myDelim); // call the function here
int tokens = 0;
for (tokens = 0 ; tokens < totalValues ; tokens++) {
printf("array_r[%d] = %0.f\n",tokens
, array_r
[tokens
]); }
}
salida
string => 1,,3
array_r[0] = 1
array_r[1] = 0
array_r[2] = 3
alguna sugerencia para que no sea flotante sino un char