在以下从这里读取文件的示例中:
#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]吗?我没有尝试这些,因为它们涉及文件操作,主要错误可能导致磁盘数据损坏。
发布于 2019-09-20 03:00:47
data变量的长度为100。如果用户输入的数据超过100,或者用于读取数据的文件长度> 100,会发生什么情况?程序的行为将是不明确的。
std::string。它的大小仅受虚拟地址空间的大小以及可用内存的限制。
string data而不是char data[100]吗?假设string是std::string,那么是的。
https://stackoverflow.com/questions/58020274
复制相似问题