How can I...

closed account (9wX36Up4)
I wrote a clock program but it writes 0 0 0 for example but i want it writes 00 00 00 How can i do that
How do you manipulate and use strings in C++? std::string/std::wstring? Or char arrays? Because the actual answer depends on how you manipulate them.

Of course, you can get a more generic answer:

-Test the length of the first value to show.
-If the length is less than 2, then prepend zeroes until the length is 2 (usually just one zero is needed).
-Repeat for the other two values to show.
closed account (9wX36Up4)
i liked the second choise u gave me actually can u write it for me?? (i don't know how to do)
I won't write it for you, but if you are going to use arrays of chars, I can re-write the steps being more specific:

-Test the length of the first value to show. If you have it in numeric form (stored in an int or similar), then totalDigits = log10(number) + 1; will tell you the number of digits.
-If you have the number in numeric form, convert to string. The C++ way of doing this is to use an ostringstream; a non-standard way would be to use itoa(), itow(), or the generic _itot() if you are using TCHAR's.
-Prepend the number of zeroes required to obtain the desired width. You can start the string inside a buffer char array and the strncpy() function, and then you add more zeroes or the value with strncat().
-Repeat for the other two values.

An alternative, if you are using std::cout to display the values, is to set character zero ('0') as the fill character of cout using fill() cout.fill() = '0'; and then setting the cout's width to 2 or whatever width you desire (pretty much the same as fill()), and then you will see that your output automatically comes with padding zeroes. I am hoping the padding zeroes will go to the right, but if not, try setting the alignment using cout.setf().

See http://www.cplusplus.com/reference/iostream/ostream/ for help using cout and streams in general.
I believe the traditional C printf format specifier can help you achieve that.

1
2
3
4
5
int main() {
  int a = 0;
  printf("%02d\n",a);
  return 0;
}

closed account (9wX36Up4)
thank u webJose i write it like this with your help
1
2
cout<<setfill('0')<<setw(2)<<Clock<<" "
<<setfill('0')<<setw(2)<<Minute<<" "<<setfill('0')<<setw(2)<<Second<<endl;
Last edited on
Topic archived. No new replies allowed.