VS编译后,显示窗口出来了,但什么也没显示,代码是书上的,唯一的不同就是主函数里那个 const char * trip = "Hawaii!!"; 书上没有 const
#include<iostream>
using namespace std;
unsigned long left(unsigned long num, unsigned ct);
char * left(const char * str, int n = 1);
int main()
{
const char * trip = "Hawaii!!";
unsigned long n = 12345678;
int i;
char * temp;
for (i = 1; i < 10; i++)
{
cout << left(n, i) << endl;
temp = left(trip, i);
cout << temp << endl;
delete[] temp;
}
return 0;
}
//显示前 ct 个数字
unsigned long left(unsigned long num, unsigned ct)
{
unsigned digits = 1;
unsigned long n = num;
if (ct == 0 || num == 0)
return 0;
while (n / 10) // n 的位数
digits++;
if (digits > ct) // n 的位数 > 需显示的位数 ct
{
ct = digits - ct; // ct = 需去掉的位数
while (ct--)
num /= 10;
return num;
}
else
return num;
}
//显示前 n 个字符
char * left(const char * str, int n)
{
if (n < 0)
n = 0;
char * p = new char[n + 1];
int i;
for (i = 0; i < n && str[i]; i++)
p[i] = str[i];
while (i <= n)
p[i++] = '\0';
return p;
}