C++ 教程目录

函数探幽

left.cpp

来源: 函数探幽

点击上方按钮打开代码编辑器和可视化视图

⚠️ 交互式运行提示

为了防止网页挂起,所有 cin 输入语句已被自动注释。请直接在代码编辑器中修改变量的值来进行测试。

书本配套例题

原始代码预览

// left.cpp -- string function with a default argument
#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;       // free old string
    ps = left(sample);
    cout << ps << endl;
    delete [] ps;       // free new string
    // cin.get();
    // cin.get();
    return 0;
}

// This function returns a pointer to a new string
// consisting of the first n characters in the str string.
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];  // copy characters
    while (i <= n)
        p[i++] = '\0';  // set rest of string to '\0'
    return p; 
}
C++ Playground
运行结果 / 调试信息
等待编译...
本节课暂无动态演示