How can I format fscanf to read strings of different lengths, some with spaces in them?

16 ビュー (過去 30 日間)
David Holman
David Holman 2017 年 10 月 11 日
コメント済み: Stephen23 2017 年 10 月 14 日
I'm trying to read comet names from a text file with fscanf and when I use %s, the read stops at the first space in the name, then considers the remaining string to be the next data field. When I use %c which is supposed to read spaces, and format %Nc using a value of N that's large enough for the largest name, the shorter names have part of the next data field (large integers) read in as part of the name. BTW, not all of the names have spaces, so '%s%s' doesn't work either. Thank you.
  1 件のコメント
Stephen23
Stephen23 2017 年 10 月 14 日
@David Holman: please upload a sample file by editing your question and clicking the paperclip button.

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

回答 (2 件)

dpb
dpb 2017 年 10 月 11 日
Can't always read a mal-formed input file; if the data strings contain embedded blanks they need to be quoted strings.
Probably the only way to do this otherwise would be to read in each full record as a string then do a lookup to a known database--but if you make the database, there's probably no reason to read the file.
  1 件のコメント
Walter Roberson
Walter Roberson 2017 年 10 月 12 日
Yup.
Is there a delimiter such as comma that marks the end of the name field?

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


Cedric
Cedric 2017 年 10 月 12 日
Wild guess:
cometNames = strtrim( strsplit( fileread( 'MyFile.txt' ), ',' )) ;
will work, provided that you adapt the delimiter to your case.
  6 件のコメント
dpb
dpb 2017 年 10 月 12 日
I'm in favor...(of both) :) It's seemed to me to becoming worse in that regards...very discouraging to get not even a sniff. Wonder if could at least record the poster's id came back--do they have that much info???
Cedric
Cedric 2017 年 10 月 13 日
I think that just imposing an email verification during the account creation (which I think/hope is the case) and giving us the possibility to at least have the TMW server send a reminder (through some button, even if we cannot add text) would be efficient. Of course it would not get people who black list mathworks, but I don't think that people are that bad in general. I guess that often they receive an email when they get an answer, and if they don't receive anymore email they believe that there is no activity (even though we are adding comments with suggestions or asking for more details).

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

カテゴリ

Help Center および File ExchangeText Data Preparation についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by