fscanf formatspec behaving not as expected

3 ビュー (過去 30 日間)
SP Lee
SP Lee 2016 年 6 月 4 日
コメント済み: Walter Roberson 2016 年 6 月 5 日
I have a text file which looks like this (attached):
1 2 3 4
a
b
c
I then do this:
>> fid=fopen('testDat.txt');
>> N=fscanf(fid,'%d%d%d%d\n\n\n%s');
>> fclose(fid)
And the ans I got is: [1;2;3;4;97]
I don't understand why, since I have 3 times of \n, the script should have skipped the blank line, 'a', 'b', and just read 'c' But it is reading all 'a','b','c'
Can explain why? Thank you
  1 件のコメント
per isakson
per isakson 2016 年 6 月 4 日
編集済み: per isakson 2016 年 6 月 4 日
See fscanf, Read data from text file. The documentation doesn't describe the effect of delimiters in formatSpec.
Removing "\" from the formatSpec doesn't change the result. Try
fid = fopen('testDat.txt');
N = fscanf(fid,'%d%d%d%d%s');
fclose(fid)
N'
displays
ans =
1 2 3 4 97
Thus, one must accept that the last word belongs to Matlab. The behavior might differ from that of the corresponding behaviour in the C-language.

サインインしてコメントする。

回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 6 月 5 日
The %s format spec is defined as skipping whitespace. Newlines are whitespace.
  3 件のコメント
per isakson
per isakson 2016 年 6 月 5 日
"The %s format spec is defined as skipping whitespace." &nbsp Is it possible to deduce that from the documentation?
Walter Roberson
Walter Roberson 2016 年 6 月 5 日
When you put something literal like \n in an fscanf string, the literal thing must be matched at that place in the input, after which it is discarded from the input. However, the rules for almost all of the format items call for skipping leading whitespace, so if you do not put the \n in, then newlines in the file are mostly going to be ignored. The %c and %[] format specifiers do not skip leading whitespace, so for example
>> N=fscanf(fid,'%d%d%d%d%c%c%c%s')
N =
1
2
3
4
10
10
97
98
and the results would be expected to be different if the file were constructed in WordPad on MS Windows as it would then have \r characters as well as \n characters.
I also find that \n in the input format will skip whitespace; for example '%d%d%d%d\n%c' will have the %c pick up the 'a' character.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by