用C++编写一个函数to_str(),将一个整型转换为一个字符串返回,这个字符串需要分配动态内存。 请根据“Append Code”完成程序。append.c中调用了一个函数to_str (),原型为char *to_str(unsized long long);Append Code为int main() { char *s; unsigned long long n; cin >> n; s = to_str(n); cout << s << endl; delete s; }
时间: 2023-06-01 12:06:02 浏览: 171
将字符串转换成整型数值
5星 · 资源好评率100%
char *to_str(unsigned long long n) {
char *str;
int len = 0;
unsigned long long temp = n;
while (temp) {
len++;
temp /= 10;
}
str = (char*)malloc(sizeof(char)*(len+1));
str[len] = '\0';
while (len--) {
str[len] = (char)(n % 10 + '0');
n /= 10;
}
return str;
}
int main() {
char *s;
unsigned long long n;
cin >> n;
s = to_str(n);
cout << s << endl;
free(s);
return 0;
}
阅读全文