知识库

C++语言开发示例:15. 左值

2025-02-01 20:35:05 李腾 1 次阅读

left.cpp

#include <iostream>

const int ArSize = 80;
char *left(const char *str, int n = 1);

int main()
{
    using namespace std;
    char sample[ArSize];
    cout << "Enter a string:\n";
    cin.get(sample, ArSize);
    char *ps = left(sample, 4);
    cout << ps << endl;
    delete[] ps;
    ps = left(sample);
    cout << ps << endl;
    delete[] ps;
}

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;
}
转载请注明转自www.hylab.cn,原文地址:C++语言开发示例:15. 左值

评论 (0)

登录后发表评论

暂无评论,快来发表第一条评论吧!