如何在C+;中自动打开输入文件+;? 在C++编写的程序中,我打开了一个文件: std::ifstream file("testfile.txt");
这种用法可以处理输入文件具有固定名称“testfile.txt”的情况。如何在C+;中自动打开输入文件+;? 在C++编写的程序中,我打开了一个文件: std::ifstream file("testfile.txt");,c++,file-io,C++,File Io,这种用法可以处理输入文件具有固定名称“testfile.txt”的情况。 我想知道如何允许用户输入文件名,例如“userA.txt”,程序会自动打开这个文件“userA.txt”。使用变量。如果你还不清楚它们是什么,我建议你找一个好的介绍 #include <iostream> #include <string> // ... std::string filename; // This is a variable of type std::string whic
我想知道如何允许用户输入文件名,例如“userA.txt”,程序会自动打开这个文件“userA.txt”。使用变量。如果你还不清楚它们是什么,我建议你找一个好的介绍
#include <iostream>
#include <string>
// ...
std::string filename; // This is a variable of type std::string which holds a series of characters in memory
std::cin >> filename; // Read in the filename from the console
std::ifstream file(filename.c_str()); // c_str() gets a C-style representation of the string (which is what the std::ifstream constructor is expecting)
您可以使用
argc
和argv
获取命令行参数
#include <fstream>
int main(int argc, char* argv[])
{
// argv[0] is the path to your executable.
if(argc < 2) return 0 ;
// argv[1] is the first command line option.
std::ifstream file(argv[1]);
// You can process file here.
}
这应该是
char*argv[]
,或者更好的char const*argv[]
;-)
#include <fstream>
int main(int argc, char* argv[])
{
// argv[0] is the path to your executable.
if(argc < 2) return 0 ;
// argv[1] is the first command line option.
std::ifstream file(argv[1]);
// You can process file here.
}
./yourexecutable inputfile.txt