Matthew Kemnetz
Matthew Kemnetz

Reputation: 855

Formatting fprintf

I have a bit of Matlab code and I am trying to export some string and create a tab-delimitted text file from it. I think fprintf performs similarly in C (if not please edit my tag). I believe my issue is with my format string. Basically I have 7 strings that I want separated by tabs and then a newline character. please note that "fid" is a full path. I am looping this in a for loop so lines are being appended each pass and the file is built.

ImgData = strcat(ImgData, fid, '\t', imgNumber, '\t', N_std,'\t',S,'\t',N,'\t',SNR,'\t',SNR_dB,'\n');
DataOut = fopen(strcat('Image_F', folderNumber, '_Data.txt'), 'w');
fprintf(DataOut,'%s\t %s\t %s\t %s\t %s\t %s\t %s\n',ImgData);

You may be curious on how this exports. This formats like

fid\tI#\tN_std\tS\tN\tSNR\tSNR_dB\n

in the txt file. As you can tell this isn't tab-delimitted which my major issue. I am having some trouble with the format string. Does anyone know how to reformat it so it prints the tabs and newline?

Upvotes: 1

Views: 4873

Answers (1)

Jonas
Jonas

Reputation: 74940

You're creating a string in ImgData that you then pass as input to fprintf. This reads ImgData into the first %s of the format string, and then adds at least one tab at the end.

What you should do instead is write something like:

`fprintf(DataOut,'%s\t%i\n',imgName,imgNumber)`

which assumes that imgName is a string and imgNumber an integer number. Note that I pass two placeholders (with the %-sign) and two input variables to fprintf.

Use %6.2f print floating point numbers with a total of 6 characters, including 2 after the comma, for SNR, for example.

For easier development, you can drop the first input argument to fprintf, in which case it will print to command line.

Upvotes: 2

Related Questions