如何使用c ++将不同长度的整个.txt文件读入数组? [英] How do i read an entire .txt file of varying length into an array using c++?

查看:328
本文介绍了如何使用c ++将不同长度的整个.txt文件读入数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个移位密码,从文件中读取文本并对其进行解码。解密工作得很好,我无法弄清楚如何找到文件的长度,没有硬编码到char数组的大小。它也只读一行,任何带有换行符的东西都会被破坏。

I'm making a shift cipher that reads in text from a file and decodes it. The decryption works fine howver i can't figure out how to find the length of the file without hardcoding it into the size of the char array. It also only reads in one line, anything with a newline in corrupts.

任何帮助都将非常感谢,我已经把代码的主块

Any help would be greatly appreciated, i've left out the main block of code as that deals with the array after it has been read in and seemed a bit long and irrelevant.

string fileName;
cout << "Please enter the locations of your encrypted text (e.g ""encryptedText.txt""): ";
getline( cin, fileName );
char encryptedMessage[446]; //How do i read in the file length and declare the array size as a variable instead of [446]?
char decryptedMessage[446];

ifstream in(fileName);
if(in.get(encryptedMessage, 446))
{
  [my decrypting code]
}
else
{
cout << "Couldn't successfully read file.\n";
}
system("pause");


推荐答案

您可以使用seekg来获取整个文件:

You can use seekg to get the size of an entire file:

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

int main () {
  long begin_byte, end_byte;
  ifstream in("example.txt");
  begin_byte = in.tellg();
  in.seekg (0, ios::end);
  end_byte = in.tellg();
  int total_bytes = end_byte - begin_byte;
  in.seekg(0, ios::begin);
  char *message = new char[total_bytes + 1];
  int index = 0;
  while (in) {
    message[index++] = in.get();
  }
  in.close();
  cout << "message is: " << message << endl;
  delete [] message;
  return 0;
}

您可以阅读更多关于c ++中的seekg,tellg和文件< a href =http://www.cplusplus.com/doc/tutorial/files/ =nofollow>此处。

You can read more about seekg, tellg and files in c++ as a whole here.

但是更好的解决方案,然后使用char *使用std:字符串,并调用push_back时,它尚未结束:

However a better solution then using char * is using a std:string and calling push_back on it while in has not ended:

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

using namespace std;

int main () {
  ifstream in("example.txt");
  string message;
  while (in) {
    message.push_back(in.get());
  }
  in.close();
  cout << "message is: " << message << endl;
  return 0;
}

这篇关于如何使用c ++将不同长度的整个.txt文件读入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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