| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
C++ help formatting int to output file
I need to take an integer and output to file with four digits, with zero’s filling the unnumbered spots. I am currently using <fstream> with ofstream to do the file output. I have found a function that will perform this to terminal, but not for output to a file. For example, if my number is 1,
What I need is 0001 If my number is 560 What I need is 0560 If my number is 25 I need 0025 . The function printf(“%04i/n”, value) where value is the variable that you want formatted will output what I want, but only to terminal, not file. If anyone can tell me how to output this to a file using <fstream>, I would greatly appreciate it. |
|
#2
|
|||
|
|||
|
You can use fprintf (file_pointer, “%04i/n”, value) if you're happy with a c style solution. If you're after a c++ version using streams then I can't help you and would also be interested to know how you do it when you find out.
-KM- |
|
#3
|
|||
|
|||
|
I know that this isn't the most speedy way to format the output, and it isnt in the form of a function, but this is the way that I have devised using <fstream> and fout.
do whatever calculations you want with your int, lets say it is called mystartpointUF. then run it through this sequence of if statements followed by the actual output of the int. (In this case I also used cout to view what I was doing on the terminal.) if( (mystartpointUF*10) < 100000) { cout<<0; fout<<0; } if( (mystartpointUF*10) < 10000) { cout<<0; fout<<0; } if( (mystartpointUF*10) < 1000) { cout<<0; fout<<0; } if( (mystartpointUF*10) < 100) { cout<<0; fout<<0; } fout<<mystartpointUF; This should work for values with a maximum of five integers and a minimum of one. If you needed larger numbers with more integers, you would just add more if statements......yay. If someone can see an obvious way to re-write this so it will run more efficiently, please let me know. I have only had two programing classes so far, and im not that good yet. Thanks in advance for any help! |
|
#4
|
|||
|
|||
|
try this!
#include<iostream.h>
#include<iomanip.h> int a; int main() { cin>>a; cout.setf(ios::right); cout<<setw(4)<<setfill('0')<<a; cin>>""; return 0; } |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > C++ help formatting int to output file |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|