c++ - ifstream + 打开随机 txt 文件 (c_str)

标签 c++ ifstream c-str

我想打开一个随机的 .txt 文件并将数据放入一些字符串中。 如果我将路径写入代码,它就会起作用。

我不明白为什么这不起作用。

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    string file;

    ifstream filein(file.c_str());

    cout << "Insert Path" << endl;
    cin >> file;

    cout << file << endl;

    filein.open(file.c_str(), ios::in);

    for (string line; getline(filein, line);) {
        cout << line << endl;
    }

    return 0;
}

最佳答案

您的文件名字符串为空,因为 std::string 默认为空。

您将一个空字符串(或 nul 字符串)传递给 ifstream 构造函数,这充其量是未定义的行为。

关于c++ - ifstream + 打开随机 txt 文件 (c_str),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41512980/

相关文章:

c++ - Eclipse 中的 C/C++,我可以使用 #define 来设置断点,但只能在单步执行代码时使用吗?

c++ - 在另一个全局仿函数中引用全局仿函数

c++ - 在 C++ 中对来自全局函数的结构成员使用方法

c++ - 从文件中读取数字并将它们存储为十进制而不是 C++ 中的 ASCII

string - c++ c_str 在字符串末尾添加奇怪的字符

c++ - 尽管签名匹配示例和源代码,但 vulkan 图形管道的参数错误

c++ - 将 std::list 转换为 C 友好类型

C++ IO 文件流 : writing from one file to another using operator<< and rdbuf()

c++ - 将 token 存储到数组中