strncmp issue

3 vues (au cours des 30 derniers jours)
Robbie
Robbie le 22 Fév 2012
Hi, I am having some trouble extracting a variable from a text file. In the text file, the data looks like :
EM = 0.7500 ALP = 1.0000
I am using some code to search for the string 'ALP =' using the strncmp function and I am trying to extract the value 1.0000 but my code deosn't work. Here is my code:
while 1
line = fgetl(fid);
if ~ischar(line),
break
end
if strncmp('EM =',dblnk(line),4),
strs=sscanf(line,'%s', 3);
em=strs(4:end);
end
if strncmp('ALP =',dblnk(line),3),
strs=sscanf(line,'%*s %*s %f %*s %*s %f ', 3);
Alpha=strs(1:end);
end
end
The code runs but doesn't return any value for ALP. If anyone has any suggestions on how to fix my code, they would be greatly appreciated.
Thanks

Réponses (1)

Walter Roberson
Walter Roberson le 22 Fév 2012
Why are you asking to read 3 elements in each sscanf() ? You only want one element of input (a string) for the EM sscanf, and you only want two elements of inputs (double precision values) for the ALP sscanf.
In your first sscanf() you read as a double but it appears you would likely prefer to read as an floating point number.
In your second sscanf() you have a mix of string and numeric formats. There is a special rule about that, but in your situation it means that what you get out would be two floating point numbers with the strings skipped. Are you sure that you want the two sections to produce two different data types?
Anyhow, your basic problem is that ALP occurs in the middle of the line but you are asking strncmp to compare only to the first 3 characters of dblnk(line). (Note by the way that 'ALP =' would be 5 characters.)
I could suggest you switch to strfind() or the like, but I think you would be better off switching to regexp() do do the processing.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by