你能将字符串转换为fstream吗? [已关闭]

问题描述 投票:0回答:1

我对带有字符串的 ifstream 和 fstream 感到好奇。我编写了一堆处理 fstream 对象并主要使用 file.get() 和 file.peek() 从文件中读取的代码。现在我被告知我必须考虑重定向和用户输入。我可以使用 ifstream 将用户字符串转换为自己的文件吗:

   cin >> input;
   ifstream file(input);
c++ string fstream ifstream
1个回答
0
投票

您可以使用

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.