[英]How to copy a .txt file to a char array in c++
我试图将整个.txt文件复制到char数组中。 我的代码可以工作,但是它没有空格。 因此,例如,如果我的.txt文件读为“ I Like Pie”,然后将其复制到myArray,如果使用for循环退出数组,则会得到“ 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");
}
有什么建议么? :/
用
myfile >> myArray[i];
您正在逐字读取文件,这会导致空格的跳过。
您可以使用以下命令将整个文件读入字符串
std::ifstream in("FileReadExample.cpp");
std::string contents((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
然后,您可以使用contents.c_str()
获得char数组。
如何运作
std::string
具有范围构造器,该构造器将复制[first,last)范围内的字符序列, 请注意,它不会以相同顺序复制last :
template <class InputIterator>
string (InputIterator first, InputIterator last);
std::istreambuf_iterator
迭代器是从流缓冲区中读取连续元素的输入迭代器。
std::istreambuf_iterator<char>(in)
将为(文件的开头) ifstream in
创建迭代器,并且如果您不向构造函数传递任何参数,它将创建流结束迭代器(最后一个位置):
默认构造的std :: istreambuf_iterator被称为流结束迭代器。 当有效的std :: istreambuf_iterator到达基础流的末尾时,它等于流结束迭代器。 取消引用或递增它会进一步调用未定义的行为。
因此,这将从文件的第一个字符开始复制所有字符,直到下一个字符在流的结尾。
使用以下代码段:
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;
如果您必须使用char数组,这是一个简单的解决方案,并且对代码的修改最少。 下面的代码段将包含所有空格和换行符,直到文件结尾。
while (!myfile.eof())
{
myfile.get(myArray[i]);
i++;
num_characters ++;
}
一个更简单的方法是使用get()成员函数:
while(!myfile.eof() && i < arraysize)
{
myfile.get(array[i]); //reading single character from file to array
i++;
}
这是您需要的代码片段:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.