Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22031

strtok returns zero with length one string

$
0
0

I'm trying to parse a CSV to a double matrix. The string could look like so "1,5\n6,4\n,4.2,6.8\0".

The variables are declared outside of the loop as follows:

double csv [MAX_SIZE, MAX_SIZE]; //initialized to a size greater then the data of the csv to parse.
char line [LINE_CAP]; //assigned per line via fgets. e.g. "1,5\n6,4\n,4.2,6.8\0"
char* token; //assigned to line segment separated per delim. e.g. 1\0

Here is the code snipped:

for (int l_cols = 0; (token = strtok(lnptr, ",")) != NULL; l_cols++) { //foreach token in line
   lnptr = NULL;
   if (l_cols > cols) {
      cols = l_cols;
   }
   double d = strtod(token, NULL);
   printf("csv[%d,%d] = '%s'", rows, cols, token);
   csv[rows][cols] = d; //convert the trimmed token to double and assign it to the csv
   printf(", converted %d, assigned %d\n", d, csv[rows][cols]);
}

Now my problem is that the second printf always return zero for the values, not 1 or 5 respectively. Example output:

[...]
A[2,3] = '1', converted 0, assigned 0
A[2,3] = '5', converted 0, assigned 0
[...]

The problem probably lies with the strtok as everything before and after looks good. Why does strtok return zero even though the string entered is a valid number, and can I fix that?


Viewing all articles
Browse latest Browse all 22031

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>