我对带有字符串的 ifstream 和 fstream 感到好奇。我编写了一堆处理 fstream 对象并主要使用 file.get() 和 file.peek() 从文件中读取的代码。现在我被告知我必须考虑重定向和用户输入。我可以使用 ifstream 将用户字符串转换为自己的文件吗:
cin >> input;
ifstream file(input);
您可以使用
ifstream
使用从用户输入获取的字符串来打开文件。
尝试这样,
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string fileName;
std::cout << "Enter the file name: ";
std::cin >> fileName;
std::ifstream file(fileName);
if (file.is_open()) {
char c;
while (file.get(c)) {
std::cout << c;
}
file.close();
} else {
std::cerr << "Unable to open the file." << std::endl;
}
return 0;
}