[英]How to read command line arguments from a text file?
我有一個程序,它接收一個 integer 和來自文本文件“./myprog < text.txt”的兩個字符串,但我希望它能夠使用命令行 arguments 來執行此操作,而無需使用“<”,例如“./myprog text.txt”,其中文本文件有 3 個輸入值。
3 <- integer
AAAAAA <- string1
AAAAAA <- string2
如果必須僅從具有其名稱的文件中讀取參數,則慣用的方法是使用getline()
。
std::ifstream ifs("text.txt");
if (!ifs)
std::cerr << "couldn't open text.txt for reading\n";
std::string line;
std::getline(ifs, line);
int integer = std::stoi(line);
std::getline(ifs, line);
std::string string1 = line;
std::getline(ifs, line);
std::string string2 = line;
因為您的文件中的行數很少,我們可以允許自己進行一些重復。 但隨着它變大,您可能需要將它們讀入向量:
std::vector<std::string> arguments;
std::string line;
while (getline(ifs, line))
arguments.push_back(line);
可以進行一些優化,例如在第一個示例中重用行緩沖區並使用std::move()
,但為了清楚起見,它們被省略了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.