How do I parse out the fields in a comma separated string into a integer array in C?
Input file date is like below-
6 1,2,77 1,5,32 1,3,54 2,4,12 4,5,52 4,3,56 6,2,8 6,5,30 3,6,44
I need those data will be stored in a array[u][v]. u = 1st column, v = 2nd column. and value of this array will be 3rd item of each row. Please help me out
Am I right that the first line gives the size of the array? I take this as an assumption.
The parsing of the string is done with
scanf()in C and the stream extractor operator in C++. It requires a bit of care to handle the commas and newlines correctly.The next problem I see is not directly related to the “parsing” problem, it is the handling of the integer array. Do you want that dynamic or static? (static means: the size of the array is known at compile time). If you want to have it dynamic you cannot use constructs like this:
array[u][v] = value;in C. In C++ you can, but you need to declare the array correctly. Both of my solutions below use dynamic arrays.C
This is a solution in pure C.
C++
here the same thing in C++. However, it does not use STL containers for the dynamic array, which could be more “elegant”.