From my understanding, he wants to put a number character in a string given that number as an integer.
Hell, just go
1 2 3
|
int x;
cin >> x; //he types a digit
str[MID_STRING]=(char)(x+48);
|
This is the most heavy-duty and cheap method, but it'll work.
For single digits! Two digits and peoples go crazy!
Well, actually, it'd substitute a pre-existing character of the string, so you'd have to shift everything as of MID_STRING one space to the right (making sure your array/vector has the space for it) first, but that's a subject for another day.
Or, you know, you could be reasonable about it.
1 2 3
|
char x;
cin >> x;
str[MID_STRING]=x;
|
Sure, you'll write 2, but since x is a char, it'll think you mean '2'.
Or, if you absolutely
must take it in as an integer... wait, no, it's always easier to take it as a string.
atoi()
will accept a
string and spit it out as an integer value (also works for >1 digit!), so if you need to do math with the value, you can just go
1 2
|
int y = atoi(x)/2;
strcpy_s(&str[MID_STRING],REMAINING_SPACE,x);
|
To go the other way around, it's
_itoa_s()
, but it's far less usable, since it doesn't return the string, but injects it into a pointer given as an argument, meaning there's a lot more work involved.
1 2 3 4 5
|
y=x/2;
char* str2 = new char[20];
_itoa_s(x,str2,20,10);
strcpy(&str[MID_STRING],REMAINING_SPACE,str2);
delete[] str2;
|
So yes, should you ever need to work with a value both as an integer (for
SCIENCE!) and as a character/string (for... a liberal arts degree?), always keep it as a character/string. If for no other reason than because atoi() > _itoa_s().