如何.txt文件复制到c进行字符数组++ [英] How to copy a .txt file to a char array in c++
问题描述
我试着去整个.txt文件复制到一个字符数组。我的code ++工程,但它留下了空白。因此,举例来说,如果我的.txt文件上写着我爱派,我把它复制到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"
下面是我的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? :/
推荐答案
通过
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>());
然后你可以使用 contents.c_str()
来获得字符数组。
这是如何工作
的std ::字符串
有一系列构造副本区间[first的字符序列,最后)注意,它不会复制去年,以相同的顺序:
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的迭代器(文件的开头),如果不传递任何参数的构造,它会创建最终OF-流迭代器(最后一个位置):
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屋!