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

将文本文档转换为字符数组C++,c++,file,dynamic-arrays,C++,File,Dynamic Arrays,我正在尝试将文本文档中的文本转换为字符数组。首先,我尝试实现一个动态数组。然而,由于某种原因,当我试图将文本中的每个字符保存到新数组中时,它会返回一组等号。下面是我所拥有的: 例如,文本中说,将其设置为字符数组 #include <iostream> #include <fstream> using namespace std; int main() { char x; int y = 0; ifstream file; file.open

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

例如,文本中说,将其设置为字符数组

#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.
另见:


顺便说一句,在不读取整个文件的情况下,根据std::ifstream确定文件大小有点棘手,请参见。

这里是另一种方法:

#include <fstream>
#include <iterator>
#include <algorithm>

int main() {
    std::ifstream file("text.txt");
    std::vector<char> text;
    std::copy(std::istream_iterator<char>(file),
        std::istream_iterator<char>(),
        std::back_inserter(text));
    // now text holds the contents of the file
    // if you really need a char array, you can use text.data()
}

请注意,代码不会测试文件是否已成功打开。当流处于错误状态时,流上的I/O操作为无操作。是的,您可以检查您是否愿意,但严格来说这不是必需的。

这里有一种方法:

std::ifstream file("text.txt", std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);

std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
    //...
}

您需要返回到文件的开头。您不能在读完所有内容后继续读取文件。使用std::vector会根据需要自动调整其内部数组的大小会更容易。这并不能解决问题,但不要在修改对象之后进行无意义的初始化。而不是ifstream文件;file.opentext.txt;使用ifstream filetext.txt;。类似地,代替char*phrase=NULL;短语=新字符[y];使用字符*短语=新字符[y];。你的代码块没有走这么远,但我敢打赌还有file.close;这也不是必需的:析构函数将关闭文件。@einpoklum-如果iostream是我的剪切粘贴文件,我也会把它搞糟。在我看来,这是拼写检查引起的错误。我冒昧地在你的回答中修正了这一点。检查。。。哦,是的。正当一切都好,结局都好,不是档案吗?这是c++17中的新语法吗?@davidshen84:-这种等价性实际上非常古老。另请参见关于ifstream的操作符@M.M:我想刚才已经修好了。另外,请随意编辑。如果file和file.rdbuf不应该这样吗?@Barmar:No-but-I-should-fix-the-indentation和yes,分别是。已编辑。+1,但我建议您无论如何都要包含一些令牌错误处理代码,否则您会秘密地将无法检查错误合法化。另外,这有多快?您确定它不会一次复制一个字符吗?在某些操作系统上,这与以文本模式打开文件的初衷不同
std::ifstream file("text.txt", std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);

std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
    //...
}