strncmp issue

조회 수: 6 (최근 30일)
Robbie
Robbie 2012년 2월 22일
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

답변 (1개)

Walter Roberson
Walter Roberson 2012년 2월 22일
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.

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by