(e-mail address removed) wrote...
Hi all,
Iam writing a small C program to print a array of numbers in
Comma Separated Values in VC++ editor.
Lets say:
Title Title1 Title2
----- ------ ------
10,20,30
50,90,100
120,180,300
I was trying to print the above values in a .txt file and the values
should be printed as above. I played a lot with different
lib.functions.But could not succeed. If anyone has implemented the
above could give me a clue to it??
In CSV format, your column headers are comma-delimited as well, all
strings (non-numbers) are in quotes, there are a fixed number of
columns in each row, empty fields are OK, and each row ends with a
newline character.
Simplest way to get this into a text file is simple to have the
program write its non-error output to stdout using printf(), and then
capture that output via redirection at the command line.
So you'd invoke it as
myprog > mycsv.txt
Your two title rows are:
#define TITLEROWFMT "\"%s\",\"%s\",\"%s\"\n"
printf( TITLEROWFMT, "Title", "Title1", "Title2" ) ;
printf( TITLEROWFMT, "-----", "------", "------" ) ;
You don't mention where you're getting your input, so I'll presume
you're generating it from within your program (rather than, say,
reading it from some other file). You also don't describe the range
of values in your output, so I'll presume an int will get the job
done.
Your data rows are:
#define DATAROWFMT "%d,%d,%d\n"
printf( DATAROWFMT, 10, 20, 30 ) ;
printf( DATAROWFMT, 50, 90, 100 ) ;
printf( DATAROWFMT, 120, 180, 300 ) ;
Presumptions and limitations:
1) I presume your question is about how to get the output into CSV
format, not how to use variables (rather than numberic constants as
in my data row example) or how to open and write to an output file.
2) Null fields are not handled by DATAROWFMT. For rows with any null
fields, you would use a different output format specifier. Here's an
example, with the first field empty:
printf( ",%d,%d\n", 50, 100 ) ;