Reputation: 29
Can someone help me with the following request:
I have a file with only one line that contains the following groups separated by a space
Here are some examples:
0 0.3 -1 +3 0xc 'N'
2.12211 1 -100 'N' 0xac 'N'
Basically the first line might contain real numbers,integer numbers,hexadecimal numbers, the character 'N' and each group is separated by a space
Is there any way to create a vector of multiple types(in C,not in C++) that will contain the elements separated by spaces(also the hexadecimal numbers should be converted to decimal numbers?
For the first example it shall be
V[0]=0
V[1]=0.3
V[2]=-1
V[3]=3
V[4]=12
v[5]='N'
For the second example it shall be
V[0]=2.12211
V[1]=1
V[2]=-100
V[3]=3
V[4]='N'
v[5]=172
V[6]='N'
Upvotes: 1
Views: 266
Reputation: 2935
Rule #1: Avoid premature optimization.
Define a type of your data:
enum data_type {
data_type_integer = 0,
data_type_float,
data_type_char,
...
};
Now define structure to contain these data:
struct data {
enum data_type data_type;
int data_integer;
float data_float;
char data_char;
};
Of course this wastes some space, but unless you write a db engine or something, remember rule #1. If it really bothers you, pack the data (not data_type
) into union. But if you make a mistake with union, it will bite you (as the compiler cannot check that, for example, you stored char
and read int
).
Now you have a single type to store various data types.
To parse it, there are various approaches. I suggest to read each item as a string and then parse the string using sscanf. The reason for this two-step approach is that you can check the string contents to determine the type: If it contains 'N', it's 'N'. If it contains 'e', 'E' or '.' it is float, etc.
Upvotes: 2
Reputation: 83537
Is there any way to create a vector of multiple types(in C,not in C++)
This seems like a good use of a union. You can define it as
union data {
float f;
int i;
char n;
};
Now declare an array of unions:
union data V[20];
And populate it like so:
V[0].i=0
V[1].f=0.3
V[2].i=-1
V[3].i=3
V[4].i=12
v[5].n='N'
In the parsing logic, you will need to decide which field of the union to use in order to ensure the correct value is stored as you intend.
Upvotes: 1