将*argv[](命令行参数)转换为无符号字符向量



在c++中,我试图将命令行*argv[]指针(3个参数)转换为无符号字符向量,即mytest 148 64 127

我得到一个向量:

vector<unsigned char> msg;

Vector包含3个无符号字符:msg = {0, 0, 0}当我尝试以这种方式转换时,

unsigned char c1 = *argv[1];
unsigned char c2 = *argv[2];
unsigned char c3 = *argv[3];
msg = {c1, c2, c3}

只得到这些字符的第一个字符。即。在命令行中输入:mytest 148 64 127

我得到:1,6和1

我建议创建一个字符串向量:

#include <iostream>
#include <vector>
int
main(int argc, char *argv[]) {
std::vector<std::string> args;
for (int i = 1; i < argc; i++) {
args.push_back({ argv[i] });
}
for (auto a: args) {
std::cout << a << std::endl;
}
return 0;
}

最简单的是转换为使用字符串。

vector<string> msg;

如果你真的想要无符号字符,那么你需要这样做:

vector<vector <unsigned char>> msg;

比起复制字符,你可以通过

保存指向argv的指针
vector<unsigned char *> msg;
msg.push_back(reinterpret_cast<unsigned char *>(argv[0]));

您只保存每个参数字符串的第一个char到您的vector

unsigned char c1 = *argv[1];

等于:

const char *str = argv[1];
unsigned char c1 = str[0]; // <-- 1st char only!

对于您正在尝试的内容,您需要将解析每个参数字符串按原样转换为它所表示的数值,以便参数字符串"148""64""127"产生整数14864127。您可以使用std::stoi()std::stol(),例如:

#include <vector>
#include <string>
//#include <cstdlib>
//#include <limits>
/*
static const int min_uc = std::numeric_limits<unsigned char>::min();
static const int max_uc = std::numeric_limits<unsigned char>::max();
*/
int main(int argc, char* argv[])
{
if (argc < 2)
{
// no arguments given, do something...
return 0;
}
std::vector<unsigned char> msg;
msg.reserve(argc-1);
for (int i = 1; i < argc; ++i)
{
int i = std::stoi(argv[i], nullptr, 0);
//int i = std::strtol(argv[i], nullptr, 0);
if ((i < 0) || (i > 255))
//if ((i < min_uc) || (i > max_uc))
{
// bad input, do something...
return 0;
}
msg.push_back(static_cast<unsigned char>(i));
}
// use msg as needed...
...
}

相关内容

最新更新