我有一个名为num.txt
who's only contents is the line的文本文件123
。然后我有以下内容:
void alt_reader(ifstream &file, char* line){
file.read(line, 3);
cout << "First Time: " << line << endl;
}
int main() {
ifstream inFile;
int num;
inFile.open("num.txt");
alt_reader(inFile, (char*)&num);
cout << "Second Time: " << num << endl;
}
输出是:
First Time: 123
Second Time: 3355185
你能帮我弄清楚如何让在函数中读取的 fstream 仍然在 main 中分配变量吗?我这样做是因为alt_reader
它确实有更多的东西,但这是我坚持的部分。非常感谢您的帮助。
更新:使用 Bill Oneal 的评论,我写了
void alt_reader(ifstream &file, stringstream &str, int n){
char buffer[n+1];
file.read(buffer, n);
buffer[n] = 0;
str << buffer;
cout << "First Time: " << buffer << endl; //First Time: 123
}
int main() {
ifstream inFile;
stringstream strm;
int num;
inFile.open("num.txt");
alt_reader(inFile, strm, 3);
cout << "Second Time: " << num << endl; //Second Time: 123
}
谢谢。对现在的情况有什么批评吗?