如何将 .txt 文件复制到 C++ 中的字符数组 [英] How to copy a .txt file to a char array in c++

查看:23
本文介绍了如何将 .txt 文件复制到 C++ 中的字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将整个 .txt 文件复制到一个字符数组中.我的代码有效,但它忽略了空格.例如,如果我的 .txt 文件读取I Like Pie"并将其复制到 myArray,如果我使用 for 循环计算我的数组,我会得到ILikePie"

Im trying to copy a whole .txt file into a char array. My code works but it leaves out the white spaces. So for example if my .txt file reads "I Like Pie" and i copy it to myArray, if i cout my array using a for loop i get "ILikePie"

这是我的代码

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{
  int arraysize = 100000;
  char myArray[arraysize];
  char current_char;
  int num_characters = 0;
  int i = 0;

  ifstream myfile ("FileReadExample.cpp");

     if (myfile.is_open())
        {
          while ( !myfile.eof())
          {
                myfile >> myArray[i];
                i++;
                num_characters ++;
          }      

 for (int i = 0; i <= num_characters; i++)
      {

         cout << myArray[i];
      } 

      system("pause");
    }

有什么建议吗?:/

推荐答案

With

myfile >> myArray[i]; 

您正在逐字阅读文件,这会导致跳过空格.

you are reading file word by word which causes skipping of the spaces.

您可以使用

std::ifstream in("FileReadExample.cpp");
std::string contents((std::istreambuf_iterator<char>(in)), 
    std::istreambuf_iterator<char>());

然后你可以使用 contents.c_str() 来获取字符数组.

And then you can use contents.c_str() to get char array.

工作原理

std::string 具有范围构造函数,它复制范围 [first,last) 中的字符序列注意它不会复制最后一个,以相同的顺序:

std::string has range constructor that copies the sequence of characters in the range [first,last) note that it will not copy last, in the same order:

template <class InputIterator>
  string  (InputIterator first, InputIterator last);

std::istreambuf_iterator 迭代器是从流缓冲区读取连续元素的输入迭代器.

std::istreambuf_iterator iterator is input iterator that read successive elements from a stream buffer.

std::istreambuf_iterator<char>(in)

将为我们的ifstream in(文件的开头)创建迭代器,如果你没有向构造函数传递任何参数,它将创建流尾迭代器(最后一个位置):

will create iterator for our ifstream in (beginning of the file), and if you don't pass any parameters to the constructor, it will create end-of-stream iterator (last position):

默认构造的 std::istreambuf_iterator 被称为流结束迭代器.当有效的 std::istreambuf_iterator 到达底层流的末尾时,它变得等于流末尾迭代器.取消引用或增加它会进一步调用未定义的行为.

The default-constructed std::istreambuf_iterator is known as the end-of-stream iterator. When a valid std::istreambuf_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. Dereferencing or incrementing it further invokes undefined behavior.

因此,这将复制所有字符,从文件中的第一个字符开始,直到下一个字符是流的结尾.

So, this will copy all characters, starting from the first in the file, until the next character is end of the stream.

这篇关于如何将 .txt 文件复制到 C++ 中的字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆