[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Integer to string function doesn't account for 0

Posted on 2006-04-11
3
Medium Priority
?
371 Views
Last Modified: 2010-08-05
I've been using this function to convert integers into wide character strings, but I realized the function fails if the integer to be converted is 0.  This happens because the for loop breaks if it finds that val = 0.  

What are some workarounds to this problem?  

wchar_t* itowcs(int val, int base)
{
      static wchar_t buf[32] = {0};
      int i = 30;
      for(; val && i ; --i, val /= base) {
            buf[i] = L"0123456789abcdef"[val % base];
      }
      return &buf[i+1];
}
0
Comment
Question by:chsalvia
3 Comments
 
LVL 85

Accepted Solution

by:
ozo earned 1000 total points
ID: 16433650
 for(; (buf[i] = L"0123456789abcdef"[val % base]) && (val/=base) && --i ; ) {

  }
  return &buf[i];
0
 
LVL 16

Expert Comment

by:PaulCaswell
ID: 16434200
Neat code ozo!
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 16435864
Why not using this function instead of re-inventing the wheel
wchar_t * _itow( int value, wchar_t *string, int radix );
Or,
wchar_t * itow( int value, wchar_t *string, int radix );
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question