Link to home
Start Free TrialLog in
Avatar of lostinspace9
lostinspace9

asked on

Formatting of C Output

I am trying to format the output of some C code and need to do something like the following incomplete VB snippet:

Val(Mid(.Text, 31,12))  
Val(Mid(.Text, 43,12))  
Val(Mid(.Text, 55,12))

As you can see I want to format the columns to be a width of 12 regardless of the value written to it.  The first column is a date & time column which I am not concerned about and then there are 11 formatted columns of other data.
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

printf lets you specify a width. So printf("%s12", string_var") should print the string_var and pad it to a width of 12. You can also use %s* and pass the width as a parameter.
http://www.cplusplus.com/reference/clibrary/cstdio/printf/

If it's C++, then you also could use iomanip with setw.
Or if you are trying to read in the values, then use strncpy.
strncpy(dest, source, 12);
strncpy(dest2, source+12, 12);
strncpy(dest3, source+24, 12);

Assuming all are character arrays.
source+12 gives you source starting at the 13th character.

If they are std::string types then all you need is the substring function.
dest3 = source.substr(24, 12);
Avatar of lostinspace9
lostinspace9

ASKER

I know that I referenced text in my question but I should have explained that the columns will contain integers and floats.  Thanks for the answer though and I will use it in the future when I actually deal with strings.
ASKER CERTIFIED SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks