c++命令行控制

该程序定义了两个C++函数,split用于按指定分隔符分割字符串,strip去除字符串两端空白。在主函数中,创建了一个命令行接口,接受用户输入的using_add命令,调用闭包函数using_add执行加法操作。使用std::stoi将字符串参数转换为整数并传递给using_add。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include
#include
#include
using namespace std;

vector split(string s, const string d)
{
if (s.empty()) return {};
vector res;
std::string strs = s + d;
size_t pos = strs.find(d);
size_t len = strs.size();
while (pos != string::npos) {
string x = strs.substr(0, pos);
if (x != “”) res.push_back(x);
strs = strs.substr(pos + d.size(), len);
pos = strs.find(d);
}
return res;
}

std::string& strip(std::string& s)
{
if (s.empty())
{
return s;
}

s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;

}

int main()
{
std::cout.precision(4);//设定输出的有效位数

char cmd_org[256];
string cmd_data;

for (;;)
{
	std::cout << "cmd>";
	std::cout.flush();
	std::cin.getline(cmd_org, sizeof(cmd_org)); //强行将缓冲区的数据清空
	cmd_data = string(cmd_org);

	vector<string>cmd_string = split(strip(cmd_data), " ");
	vector<string>cmd_list;
	for (auto cmd_str : cmd_string)
	{
		cmd_list.push_back(cmd_str);
	}

	if (cmd_list.size() !=2)
		continue;

	if (cmd_list[0] != "using_add")
		continue;

	int abc = 0;
	auto using_add = [&abc](int mode)
	{
		if (mode == 0)
		{
			abc += 1;
		}
		else
		{
			abc += 2;
		}
	};
	
	using_add(std::stoi(cmd_list[1]));
	cout << abc << endl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值