Qbasicnews.com

Full Version: C/C++ int to string?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Here's one way of converting an int to string in C++. It seems very clunky, is there a better way?
Code:
#include <sstream>
ostringstream oss;
oss << 5;
string myString = oss.str();
char *cString = myString.c_str();
Quote:#include <stdlib.h>
char *itoa(int value, char *string, int radix);

Description
Converts an integer to a string.
itoa converts value to a null-terminated string and stores the result in string. With itoa, value is an integer.
radix specifies the base to be used in converting value; it must be between 2 and 36, inclusive. If value is negative and radix is 10, the first character of string is the minus sign (-).

Note: The space allocated for string must be large enough to hold the returned string, including the terminating null character (\0). itoa can return up to 17 bytes.

Return Value

itoa returns a pointer to string.

Mmm, gooooogle....
I don't see the reason why a purportedly (SP?) efficient language like C would even have a string conversion. Strings are made up of bytes, so why not just recognize them as dynamic byte (or integer or double integer) arrays, and when using them as 'a$ = "Hi I'm a string"' just have the compiler convert to the array equivalent?
Strings are arrays of chars:

Code:
#include <stdio.h>
#include <string.h>

int main() {
  int i;
  char *string = "Hello World\n";
  
  for(i = 0; i < strlen(string); i++) {
    printf("%c\n", string[i]);
  }
}

String conversion exists for portability reasons. If you just grabbed the first byte of the above string you would have the value of the letter 'H' in whatever character set you are using (ascii, unicode, etc), the value isnt guaranteed to be the same everywhere, so the standard C library provides functions for doing the conversion. That way, only the library function every needs changing and any code that uses it will be portable to other character sets.
Thanks for the help.

What I really want to do is just load, say 10 bitmaps ("p1.bmp" to "p10.bmp") so where it's nice n easy in QB, I can see I'm just gonna have to mess around a bit more.

Code:
'assuming we had a bmpLoad sub ;)
for i = 1 to 10
   bmpLoad "p"+ltrim$(str$(i))+".bmp"
next
sniff..
well, the easy way is to use letters and ascii characters, off the top of my head Tongue
I used this trick to load from 0 to 9:

Code:
char filename = "tile_.txt";

for(i=0; i<10; i++)
{
   filename[4] = i+ '0';     // Stupid conversion dec -> ASCII
   load_stuff(filename);
}
sprintf is also great, you can do something like

sprintf(string,"tile%d.bmp,looper);

and itll work fine Smile
yup, I forgot about that... *that's* the sollution Wink great, HR
Code:
// int to string converter
string str ( int i )
{
    char buffer[100];
    _itoa(i, buffer, 10);
    return (string(buffer));
}
Pages: 1 2