keep fscanf past wrong format value

10 Ansichten (letzte 30 Tage)
Santiago
Santiago am 15 Mai 2023
Beantwortet: Walter Roberson am 15 Mai 2023
Hello, im having this problem with feof function and fscanf. I want to read all the whole numbers but it stops when it reaches something that is not. How can I make it ignore that and keep scanning?
fid = fopen("testdata.txt","r");
a = [];
i = 0;
while ~feof(fid)
i = i + 1;
a(i) = fscanf(fid, '%d', 1);
end
Unable to perform assignment because the left and right sides have a different number of elements.
fclose(fid);
  1 Kommentar
Rik
Rik am 15 Mai 2023
Wouldn't you be better off reading the entire file and then matching each line with a regular expression?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 15 Mai 2023
Unless you have integers that might have value outside of +/- 2^53 then there is little point using a %d format. Use a %f format instead: that will accept floating point numbers without any reading problems. You can always check that everything is integer afterwards.

Weitere Antworten (0)

Kategorien

Mehr zu Low-Level File I/O finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by