在我用C++编写的程序,我打开一个文件,如下所示:如何在C++中自动打开输入文件?
std::ifstream file("testfile.txt");
这种用法可以处理其中输入文件具有“TESTFILE.TXT”的固定名称的情况。 我想知道如何让用户输入文件名,例如“userA.txt”,程序自动打开这个文件,“userA.txt”。
在我用C++编写的程序,我打开一个文件,如下所示:如何在C++中自动打开输入文件?
std::ifstream file("testfile.txt");
这种用法可以处理其中输入文件具有“TESTFILE.TXT”的固定名称的情况。 我想知道如何让用户输入文件名,例如“userA.txt”,程序自动打开这个文件,“userA.txt”。
使用变量。如果你不清楚他们到底是什么,我建议找一个好的介绍book。
#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)
如果文件名可具有在它的空间,然后cin >>
(其停止在第一空间输入以及换行)将不会削减它。相反,你可以使用getline()
:
getline(cin, filename); // Reads a line of input from the console into the filename variable
您可以获得命令行参数与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.
}
的命令行用法是:
./yourexecutable inputfile.txt
这应该是'字符* argv的[]',甚至更好'字符常量*的argv []';-) – Cameron 2011-03-20 22:57:22
@Cameron:您比我的编辑速度快:) – 2011-03-20 22:58:08