قابلت سؤال عن كتابة دالة تستقبل رقم integer ومصفوفة حروف char array وتعيد مؤشر الى حرف char pointer
تقوم بتحويل الرقم الى نص وتخزنه فى المصفوفة الحرفية
فكتبت الكود التالى
// test.cpp
#include <iostream>
using std::cout;
using std::endl;
char* itoa(int i,char b[]);
int main(int argc,char* argv[]){
char b[9];
cout << itoa(argc,b) << endl;
return EXIT_SUCCESS;
}
// accept decimal,octal,hexadecimal put print as decimal
char* itoa(int i,char b[]){
bool print = false;
int base = 100000000;
int res = 0;
int index = 0;
do{
res = i / base;
if(res) print = true; // once only
if(print) b[index++] = res + '0';
i %= base;
base /= 10;
}while(base > 0);
b[index] = '\0'; // terminate the char array
return b;
}اظنها تقوم بالمطلوب مع خبرتى القليلة طبعا
لكن احس ان هناك حل افضل
ملحوظة :
اعرف انه يمكننى التحويل الى نص باستخدام ostringstream ولكن لا اريد هذه الطريقة (على الاقل الان)
بانتظار مقترحاتكم
شكرا