![](/img/trans.png)
[英]How to input a string or integer to a C++ program from the command line?
[英]C++, how to provide the input filename from the command line, without hardcoding it in the program?
這是我之前的問題的繼續, 在C ++中,如何讀取文本文件的內容,並將其放在另一個文本文件中?
在那,我能夠打開一個輸入文件input.txt
並成功讀取它的內容,但現在我不想硬編碼或事先給出輸入文件名,
ifstream myfile ("input.txt");
if (myfile.is_open())
但是我想在編譯程序之后給出輸入文件名,並在命令行中生成一個名為test
的可執行文件,如下所示
./test input.txt
有關如何做到這一點的任何建議?
您可以在main
函數中訪問傳遞給程序的命令行參數:
int main(int argc, char *argv[]) { }
argc
是傳遞給程序的參數數量, argv
包含指向傳遞給程序的參數的C字符串的指針。 因此,使用此數組可以訪問傳遞給程序的參數。
但是你必須要注意:程序本身總是作為第一個參數傳遞給程序。 所以argc總是至少有一個而argv[0]
包含程序名。
如果你想從帖子中訪問input.txt
,你可以寫:
int main(int argc, char *argv[]) {
if (argc > 1) {
// This will print the first argument passed to your program
std::cout << argv[1] << std::endl;
}
}
只需添加所有答案 - 您可以使用C / C ++的' 標准輸入和輸出 ',如printf() & scanf()
$ ./a.out < input.file // input file
$ ./a.out > output.file // output file
$ ./a.out < input.file > output.file // merging above two commands.
有關更多信息:請參閱此處
當然,干凈的方式是使用argc / argv作為其他紳士的回答。
這就是argv
和argc
的用途。
int main(int argc, char **argv)
{
assert(argc >= 2); // Not the best way to check for usage errors!
ifstream myfile(argv[1]);
…
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.