如何将命令行参数变成一个向量,每个字符都作为不同的值?

How do I make a command line argument into a vector with each character as a different value?

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
/*
void square(cLine, height){

}
*/
//void insertVector(vector<char> & cLine, )
int main(int argc, char *argv[]){
    if (argc != 5){
        cerr << "Incorrect number of arguments" << endl;
        return 1;
    }
    ofstream writeFile(argv[4]);
    if (!writeFile.good()){
        cerr << "Bad file, could not open" << endl;
        return 1;
    }
    int arrayLength = sizeof(argv[1]);
    vector<string> cLine;
    string cString(argv[1]);
    for(int i=0,i<arrayLength-2,++i){
        cLine.push_back(cString.substr(i,i+1));
    }
    cout << cLine << endl;
}

我正在尝试将一个参数 argv[1] 变成一个向量,这样我以后可以很容易地拼接它,我知道这个参数是一个 c 风格的 char* 数组,但我不知道如何转换它变成一个向量,其中每个索引都是一个字符,但可以打印到控制台。

这个声明

int arrayLength = sizeof(argv[1]);

没有意义,因为 sizeof(argv[1]) 等同于 sizeof( char * ) 并且不会产生参数中的字符数。

此声明

cout << cLine << endl;

也没有意义,因为模板 class std::vector.

没有重载 operator <<

而且这个for循环

for(int i=0,i<arrayLength-2,++i){

语法不正确。

您需要的是以下内容

#include <cstring>

//…

std::vector<char> cLine( argv[1], argv[1] + std::strlen( argv[1] ) );
for ( const auto &c : cLine ) std::cout << c;
std::cout << '\n';

您可以从参数中创建 std::string(有点类似于 std::vector)。它会让您轻松做自己想做的事。

我将参考构造函数编号 @ std::basic_string 和代码中的 std::vector

#include <iostream>
#include <string>
#include <vector>

int cppmain(std::string program, std::vector<std::string> args) {
    if(args.size() != 4) {
        std::cerr << "Incorrect number of arguments\n";
        return 1;
    }

    std::cout << program << " got arguments:\n";
    for(std::string& arg : args) {
        std::cout << " " << arg << "\n";
    }

    std::cout << program << " got arguments (alt. version):\n";

    for(size_t i = 0; i < args.size(); ++i) {
        std::cout << " " << args[i] << "\n";
    }

    std::cout << "the first argument, char-by-char:\n";

    for(char ch : args[0]) {
        std::cout << ch << '\n';
    }

    std::cout << "the first argument, char-by-char (alt. version):\n";

    for(size_t i = 0; i < args[0].size(); ++i) {
        std::cout << args[0][i] << '\n';
    }

    if(args[0].size() >= 6) {
        std::cout << "printing a range (start=2, length=4) of the first argument:\n";
        std::cout << args[0].substr(2, 4) << '\n';
    }

    return 0;
}

// Let main() create a std::string out of the program name (argv[0]) using
// std::string constructor 5
//
// and a std::vector<std::string> out of the arguments using
// std::vector constructor 5 (iterators).
//
// {argv+1, argv+argc}  becomes arguments to the  args  parameter in cppmain()
//
// argv+1    points at the first program argument argv[1] (the begin iterator)
// argv+argc points one step beyond the last program argument (the end iterator)

int main(int argc, char* argv[]) {
    return cppmain(argv[0], {argv + 1, argv + argc});
}