#include <iostream>
#include <string>
using namespace std;
void print(string s)
{
cout << "第一种:" << endl;
if (s.length() > 10)
cout << s.substr(0, 10) << endl;
else
cout << s << endl;
}
void print(string s, int n)
{
cout << "第二种:" << endl;
if (s.length() > n)
cout << s.substr(0, n) << endl;
else
cout << s << endl;
}
void main()
{
string s;
cout << "请输入字符:";
cin >> s;
int n;
cout << "n=";
cin >> n;
print(s);
print(s, n);
}
设计一个函数print打印字符串,如果只传string型参数s,则字符串长度跟10比较,大于10,打印前10个字符,小于10,全部输出s;如果传string型参数s和int型n,则字符串长度跟n比
最新推荐文章于 2022-11-07 11:25:27 发布
该程序展示了如何在C++中使用`substr`函数根据字符串长度进行截取,并结合`cin`和`cout`进行用户输入输出操作。程序首先获取用户输入的字符串,然后分别按不同条件打印字符串的前10个字符或用户指定数量的字符。
摘要由CSDN通过智能技术生成