无大小限制读取文件数据

Reading file data without size limitation

在以下从 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. The data variable is of length 100. What will happen if user enters data longer than 100 or if the file used to read into data has length > 100?

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

  1. What can we use so that there is no limitation of size for data?

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

  1. Can we use string data rather than char data[100] here?

假设stringstd::string,那么是。