首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取文件数据,不受大小限制

问读取文件数据,不受大小限制
EN

Stack Overflow用户
提问于 2019-09-20 00:23:33
回答 1查看 43关注 0票数 0

在以下从这里读取文件的示例中:

代码语言:javascript
复制
#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]吗?

我没有尝试这些,因为它们涉及文件操作,主要错误可能导致磁盘数据损坏。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-20 03:00:47

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

程序的行为将是不明确的。

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

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

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58020274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档