c++ - 将文本文档转换为字符数组 C++

标签 c++ file dynamic-arrays

我正在尝试将文本从文本文档转换为字符数组。首先,我尝试实现一个动态数组。但是,出于某种原因,当我尝试将文本中的每个字符保存到新数组中时,它会返回一堆等号。下面是我所拥有的:

例如,文本说“将其设为字符数组”之类的话。

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char x;
    int y = 0;
    ifstream file;
    file.open("text.txt");
    while (file >> x)
        y++;

    char *phrase = NULL;
    phrase = new char[y];

    for (int i = 0; file >> x; i++)
    {
        phrase[i] = x;
    }
    for (int i = 0; i < y; i++)
    {
        cout << phrase[i];
    }
}

它最终会输出:“==================”

我对这个问题进行了研究,但找不到任何可以解决的问题。

最佳答案

您似乎是通过重复读取文件中的单个字符来“测量”文件的长度。您不需要这样做 - 只需在打开文件之前确定大小即可:

#include <filesystem>
#include <fstream>  

int main() {
    auto file_name { "text.txt" };
    auto size = std::filesystem::file_size(file_name);
    std::ifstream file(file_name);
    // etc. etc.

请参阅 file_size() 的文档功能。它在 C++17 中;如果您使用的是该语言的早期版本,请尝试使用 C++14 的 >experimental/filesystem>,否则 boost::filesystem任何版本的 C++ 库。

...但实际上,您根本不需要这样做!

您可以使用普通的 C++ 标准库工具读取整个文件:

#include <sstream>
#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("text.txt");
    if (not file) { /* handle error */ }
    std::stringstream sstr;
    sstr << file.rdbuf(); // magically read all of the file!
    auto entire_file_contents = sstr.str();
    const char* arr = entire_file_contents.c_str();
    // Now do whatever you like with the char array arr
}

另见:What is the best way to read an entire file into a std::string in C++?

顺便说一句,在给定 std::ifstream 的情况下不读取整个文件来确定文件的大小有点棘手,请参阅 this answer .

关于c++ - 将文本文档转换为字符数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50807199/

相关文章:

c++ - std::any std::unique_ptr 不起作用?

c++ - 递归函数可以内联吗?

java - 无法以编程方式从android中的外部存储中删除文件

python - 使用 python 和 NumPy 生成大型随机文本文件

delphi - 需要一次将任何扩展名为XE5的一个字节的文件读入动态数组

c++ - 进程内通信 WinRT(消息替换)

c++ - 使用 BOOST ASIO async_read_until 读取 mpstat 输出时文件意外结束

Java搜索文件

c++ - 数组随机访问 C++

安卓动态数组