我一直在努力做的是...
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.
}
}
理想情况下,我想以这种方式调用此方法。
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/