如何在C++中自动打开输入文件?

use*_*850 2 c++ file-io

在我用C++编写的程序中,我按如下方式打开一个文件:

std::ifstream file("testfile.txt");
Run Code Online (Sandbox Code Playgroud)

此用法可以处理输入文件具有固定名称"testfile.txt"的情况.我想知道如何允许用户输入文件名,例如"userA.txt",程序会自动打开这个文件"userA.txt".

Cam*_*ron 7

使用变量.如果你不清楚它们到底是什么,我建议找一本好的入门.

#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)
Run Code Online (Sandbox Code Playgroud)

如果文件名中可以​​包含空格,那么cin >>(在第一个空格和换行符处停止输入)将不会删除它.相反,你可以使用getline():

getline(cin, filename);    // Reads a line of input from the console into the filename variable
Run Code Online (Sandbox Code Playgroud)