c++ parse argv
#include <iostream>
#include <format>
int main(int argc, char* argv[])
{
if (argc > 1) {
char prefix;
char* opt;
int valIndex;
char* val;
for (size_t i = 1; i < argc; i++)
{
prefix = *argv[i];
if (prefix == '-')
{
opt = (argv[i] + 1);
switch (*opt)
{
case 'i':
valIndex = ++i;
if (valIndex < argc) {
val = argv[valIndex];
std::cout << val << "\n";
}
break;
case 'o':
valIndex = ++i;
if (valIndex < argc) {
val = argv[valIndex];
std::cout << val << "\n";
}
break;
default:
std::cout << std::format("Error:未知的选项 '{}'", argv[i]) << "\n";
return 1;
}
}
else
{
std::cout << std::format("Error:未知的前缀 '{}'", prefix) << "\n";
return 1;
}
}
}
else
{
std::cout << std::format("没有参数") << "\n";
}
return 0;
}
测试:
> t.exe -i "input" -i "output"
input
output
> t.exe -a "asd.txt"
Error:未知的选项 '-a'
> t.exe -i "input" -i
input
> t.exe +i "input"
Error:未知的前缀 '+'