【问题标题】:Reading file data without size limitation无大小限制读取文件数据
【发布时间】:2019-09-20 00:23:33
【问题描述】:

在下面从here读取文件的例子中:

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

int main () {
   char data[100];

   // open a file in write mode.
   ofstream outfile;
   outfile.open("afile.dat");

   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);

   // write inputted data into the file.
   outfile << data << endl;

   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();

   // again write inputted data into the file.
   outfile << data << endl;

   // close the opened file.
   outfile.close();

   // open a file in read mode.
   ifstream infile; 
   infile.open("afile.dat"); 

   cout << "Reading from the file" << endl; 
   infile >> data; 

   // write the data at the screen.
   cout << data << endl;

   // again read the data from the file and display it.
   infile >> data; 
   cout << data << endl; 

   // close the opened file.
   infile.close();

   return 0;
}

我的问题是:

  1. data 变量的长度为 100。如果用户输入的数据长度超过 100,或者用于读取数据的文件长度 > 100,会发生什么情况?

  2. 我们可以使用什么来不受数据大小的限制?

  3. 我们可以在这里使用string data而不是char data[100]吗?

我没有尝试这些,因为这些涉及文件操作,并且重大错误会导致磁盘数据损坏。

【问题讨论】:

  • 1. Well documentedgetline 读取它可以读取的内容,并通过进入失败状态并拒绝继续读取来强制您处理问题,直到错误为cleared。 2. 使用std::stringstd::getline 3. 是的,但是你必须使用std::getline 而不是std::istream::getline
  • 道歉。我错过了后来的infile &gt;&gt; data;。这只是简单的 ,因为它不知道 100 个字符的限制。这将徘徊在data 结尾处的未定义行为。解决方案是再次使用std::string
  • 如果您需要处理一个比您拥有的可用内存还大的不确定且非常大的数据集,您需要分块处理它。阅读一部分,处理/显示它,释放它,然后继续下一部分,并继续这样做,直到你到达终点。
  • 这说明了很多。谢谢。

标签: c++ arrays string file-io char


【解决方案1】:
  1. data 变量的长度为 100。如果用户输入的数据长度超过 100,或者用于读入数据的文件长度 > 100,会发生什么情况?

程序的行为将是未定义的。

  1. 我们可以使用什么来不受数据大小的限制?

std::string。它的大小仅受虚拟地址空间大小以及可用内存的限制。

  1. 我们可以在这里使用string data 而不是char data[100] 吗?

假设stringstd::string,那么是的。

【讨论】:

  • 所以我可以这样做:string data; infile &gt;&gt; data ?
猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 2010-10-26
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多