C++如何传递命令行参数来读取txt文件

标签 c++ command-line-arguments

我一直在努力做的是...

1) 通过命令行参数读取txt文件,

2) 使用 txt 文件中的字符串作为 main 方法(或您需要调用的任何方法)的参数。

例如有两个txt文件,一个名为character.txt,另一个为match.txt。

文件的内容应该是这样的。

字符.txt

//This comprises of six rows. Each of the rows has two string values
Goku Saiyan
Gohan Half_Saiyan
Kuririn Human
Piccolo Namekian
Frieza villain
Cell villain

匹配.txt

//This comprises of three rows, each of them is one string value
Goku Piccolo
Gohan Cell
Kuririn Frieza

如果我在不使用命令行的情况下使用这些字符串,我会像这样在 character.txt 中声明这些字符串。

typedef string name; //e.g. Goku
typedef string type; //e.g. Saiyan, Human, etc

现在我正在寻找如何从 txt 文件读取和发送字符串值,如上面的那些,并将它们用于 main 方法内的函数,理想情况下是这样。

int main(int argc,  char *argv)
{
    for (int i = 1; i < argc; i++) {

        String name = *argv[i]; //e.g. Goku
        String type = *argv[i]; //e.g. Saiyan, Human, etc
        String match = * argv[i]; //Goku Piccolo
        //I don't think any of the statements above would be correct.
        //I'm just searching for how to use string values of txt files in such a way

        cout << i << " " << endl; //I'd like to show names, types or matchs inside the double quotation mark. 
    }
}

理想情况下,我想以这种方式调用此方法。 enter image description here

According to this web site. ,至少我知道可以在 C++ 中使用命令行参数,但我找不到更多信息。如果您能就此提出任何建议,我将不胜感激。

附言。我正在使用 Windows 和代码块。

最佳答案

假设您只想读取文件的内容并处理它,您可以从这段代码开始(没有任何错误检查)。它只是从命令行获取文件名并将文件内容读取到 2 个 vector 中。然后您可以根据需要处理这些 vector 。

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

std::vector<std::string> readFileToVector(const std::string& filename)
{
    std::ifstream source;
    source.open(filename);
    std::vector<std::string> lines;
    std::string line;
    while (std::getline(source, line))
    {
        lines.push_back(line);
    }
    return lines;
}

void displayVector(const std::vector<std::string&> v)
{
    for (int i(0); i != v.size(); ++i)
        std::cout << "\n" << v[i];
}

int main(int argc,  char **argv)
{
    std::string charactersFilename(argv[1]);
    std::string matchesFilename(argv[2]);
    std::vector<std::string> characters = readFileToVector(charactersFilename);
    std::vector<std::string> matches = readFileToVector(matchesFilename);

    displayVector(characters);
    displayVector(matches);
}

关于C++如何传递命令行参数来读取txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30141000/

相关文章:

haskell - 没有等号的 cmdargs 值参数

C++ 在公共(public)函数中使用 system() 安全还是不安全?

c++ - 一个实例会影响另一个实例,尽管它不应该

c# - 在没有管理员权限的情况下使用 'schtasks' 调度任务 C#

C++ 命令行参数识别

c++ - 允许表单接受命令行参数

c - 在 C 中,处理类似 "list"的多个参数的典型方法是什么?

c++ - C++使用删除的函数错误进行条件初始化

c++ - 智能指针列表 - 管理对象生命周期和指针有效性

C++模板模板中的此类分配是什么意思?