【发布时间】: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;
}
我的问题是:
data变量的长度为 100。如果用户输入的数据长度超过 100,或者用于读取数据的文件长度 > 100,会发生什么情况?我们可以使用什么来不受数据大小的限制?
我们可以在这里使用
string data而不是char data[100]吗?
我没有尝试这些,因为这些涉及文件操作,并且重大错误会导致磁盘数据损坏。
【问题讨论】:
-
1. Well documented。
getline读取它可以读取的内容,并通过进入失败状态并拒绝继续读取来强制您处理问题,直到错误为cleared。 2. 使用std::string和std::getline3. 是的,但是你必须使用std::getline而不是std::istream::getline -
道歉。我错过了后来的
infile >> data;。这只是简单的,因为它不知道 100 个字符的限制。这将徘徊在 data结尾处的未定义行为。解决方案是再次使用std::string。 -
如果您需要处理一个比您拥有的可用内存还大的不确定且非常大的数据集,您需要分块处理它。阅读一部分,处理/显示它,释放它,然后继续下一部分,并继续这样做,直到你到达终点。
-
这说明了很多。谢谢。
标签: c++ arrays string file-io char