如何将 .txt 文件复制到 C++ 中的字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18398167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:56:59  来源:igfitidea点击:

How to copy a .txt file to a char array in c++

c++arrays

提问by user2710184

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"

我试图将整个 .txt 文件复制到一个字符数组中。我的代码有效,但它忽略了空格。因此,例如,如果我的 .txt 文件读取“我喜欢 Pie”并将其复制到 myArray,如果我使用 for 循环计算我的数组,我会得到“ILikePie”

Here is my code

这是我的代码

#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");
    }

any suggestions? :/

有什么建议?:/

回答by Nemanja Boric

With

myfile >> myArray[i]; 

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

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

You can read entire file into the string with

您可以使用以下命令将整个文件读入字符串

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

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

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

How this works

这是如何工作的

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

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

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

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

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

std::istreambuf_iterator<char>(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):

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

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.

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

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

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

回答by Didac Perez Parera

Use the following code snippet:

使用以下代码片段:

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);

char *string = (char *)malloc(fsize + 1);
fread(string, fsize, 1, f);
fclose(f);

string[fsize] = 0;

回答by HyperionX

A simple solution if you're bound to using char arrays, and minimal modification to your code. The snippet below will include all spaces and line breaks until the end of the file.

如果您必须使用字符数组,并且对代码的修改最少,那么这是一个简单的解决方案。下面的代码段将包含直到文件末尾的所有空格和换行符。

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

回答by Theja

A much simpler approach would be using the get() member function:

一个更简单的方法是使用 get() 成员函数:

while(!myfile.eof() && i < arraysize)
{
    myfile.get(array[i]); //reading single character from file to array
    i++;
}

回答by GeneralCode

Here is the code snippet you need:

这是您需要的代码片段:

#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>


int main()
{
  std::ifstream file("name.txt");
  std::string str((std::istreambuf_iterator<char>(file)),
                        std::istreambuf_iterator<char>());

  str.c_str();

  for( unsigned int a = 0; a < sizeof(str)/sizeof(str[0]); a = a + 1 )
  {
    std::cout << str[a] << std::endl;
  }

  return 0;
}