this is prob pretty easy but if someone could explain the easiest way to get ‘sval’ to contain the string “$1” – “$500” for array indexes 0-499. in the following code, however itoa is giving me strange strings in the code below:
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct data_t {
int ival;
char *sval;
} data_t;
void f1(data_t **d);
int main()
{
data_t *d;
d = new data_t[500];
f1(&d);
}
/* code for function f1 to fill in array begins */
void f1(data_t **d)
{
char str[5];
for (int i=0; i<500; i++)
{
(*d)[i].ival = i+1;
itoa (i+1,str,10);
(*d)[i].sval = str;
}
}
it also seems itoa has been depreciated, but that was what i got when i googled int to string
or... trying it with stringstream i still get problems and i'm nowhere getting the '$' in the front, yet...
#include<iostream>
#include<sstream>
using namespace std;
typedef struct data_t {
int ival;
char *sval;
} data_t;
void f1(data_t **d);
int main()
{
data_t *d;
//d = static_cast<data_t*>(malloc(sizeof(data_t)*500)); //for legacy c
d = new data_t[500];
f1(&d);
}
/* code for function f1 to fill in array begins */
void f1(data_t **d)
{
stringstream ss;
char *str;
for (int i=0; i<500; i++)
{
(*d)[i].ival=i+1;
ss << i;
str = ss.str();
(*d)[i].sval= str;
}
}
char * and string do not work well together... and again.. i'm still not sure how to get the "$" in front of the whole thing... ugh
oh... and if it helps.. this is the code given: and my requirements The following program contains an array of structures of type data_t. The declaration for the variable ‘d’ of type data_t is given. Write logic into the main program to allocate memory for variable ‘d’ such it contains an array of 500 elements, each of type data_t. Don’t bother with freeing the memory or testing the return value of malloc for NULL. Then, write function ‘f1’ to fill in each of the 500 elements of the array such that the integer field ‘ival’ has the values 1-500 for array indexes 0-499 respectively, and the string field ‘sval’ contains the string “$1” – “$500” for array indexes 0-499 respectively. The call for function ‘f1’ is given at the end of the main program.
typedef struct data_t {
int ival;
char *sval;
} data_t;
main()
{
data_t *d; /* declaration for an array of data_t structures */
/* allocate memory for a 500 element array of structures begins */
/* allocate memory for a 500 element array of structures ends */
f1(&d); /* function call to fill in array */
}
/* code for function f1 to fill in array begins */
f1(data_t **d)
{
}
/* code for function f1 to fill in array ends */