YMD YMD - 24 days ago 8
C++ Question

C++ How to pass command line argument to read txt file

What I've been trying to do is...

1) to read txt files by command line argument,

2) to use strings in the txt files as arguments for the main method (or whatever method you need to invoke).

For example, there are two txt files, one of which is named character.txt and the other match.txt.

The contents of the files would be like this.

character.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


match.txt

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


If I use those strings without using command line, I'd declare the strings in character.txt like this.

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


Now I'm looking for how to read and send string values from txt files like the ones above, and to use them for functions inside the main method, ideally like this way.

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.
}
}


Ideally, I'd like to invoke this method in this way.
enter image description here

According to this web site., at least I understand it is possible to use command line arguments with C++, but I cannot find any more information. I'd appreciate if you'd give any advice on it.

PS. I'm using Windows and Code Blocks.

Answer

Asuming you just want to read contents of the files and process it, you can start with this code (Without any errors checks tho). It simply gets filenames from command line and reads file contents into 2 vectors. Then you can just process these vectors as u need.

#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);
}