MATLAB: How to treat space in a text file as leading zeros

fscanfleadingMATLABspacetextscanzero

I am reading in numbers from a text file to a string. For example, consider the string below, which contains 4 integers: 99919, 99920, 100000, 99997:
>> str=' 99919 99920100000 99997'
Each takes up exactly 6 characters in the string, with leading zeros shown as spaces. I am trying to use "textscan" to read these numbers one-by-one,
>> t = textscanf(str,'%6d')
>> celldisp(t)
but it is not working as expected.

Best Answer

The "textscan" function cannot interpret spaces as numbers, so the best solution would be to convert all spaces to leading zeros.
To start, read the contents of your file into a single character vector, using "fileread". Convert all spaces in the character vector to leading zeros. Then, use "textscan" as before. For example, using the attached text file:
>> str = fileread('t.txt');
>> str(str == ' ') = '0';
>> t =textscan(str,'%6d');
>> celldisp(t)