We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello, I have tried several options to parse my array of data in my txt file to floats for future use.
I believe the issue is that the format of the txt file is [1.0, 30.0, 0.0] . Therefore, I need to trim the initial [ when iterating through the lines of the file. However, I don't seem to be able to find the correct method within my code.
I have commented beside the methods tried with the errors I get when using these methods. Could anyone point me in the right direction? Many thanks
String line;
void setup() {
size(112, 84);
background(0);
noStroke();
loadCurve();
}
void draw() {
}
void loadCurve() {
String[] data = loadStrings("curve.txt");
println("there are " + data.length + " lines");
for (int i = 0; i < data.length; i++) {
String[] coords = split(data[i], ',');
String [] trimcoords = trim(coords);
//print to console as a string works fine.
//println(coords[0] + coords[1]);
//when done like this I get NaN error
//float x=float(trimcoords[0]);
//when done like this I get number format exception
float x = Float.parseFloat(trimcoords[0]);
float y = Float.parseFloat(trimcoords[1]);
println(x +','+ y);
}
}
Answers
Not to worry I solved it using this solution found in another forum thread.
Thanks
I believe what you need is splitTokens(): https://processing.org/reference/splitTokens_.html
Kf
Be careful with splitTokens() if you are working with data as opposed to arbitrary strings. It is bad for e.g. comma-delimited data. It is a string splitter, not a CSV parser.
For example, you would expect
...to split like this:
But instead,
splitTokens()
returns this:For CSV data, use loadTable() -- unless you are generating your data and you are absolutely sure that your data is regular.
ReplaceAll() will merge common and adjacent delimiters doing exactly what splitTokens does. Just to add, the dangers (or feature) of splitTokens is described in the reference. Nevertheless it is important to consider this note as part of your design.
Kf