我有一个名为num.txt的文本文件,唯一的内容是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

您能帮我弄清楚如何获得仍在main中分配变量的函数中读取的fstream吗?我这样做是因为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
}

谢谢。现在有什么批评吗?

最佳答案

第一次打印变量时,将其打印为char *,并打印将文件视为文本文件(很幸运,您没有崩溃)。第二次打印时,将其重新解释为int,使表示形式完全不同。

每当将指针从一种类型转换为另一种类型时,通常都会调用未定义的行为。由于charint没有标准关系,因此请在此处获取。

编辑:要回答您的评论问题:

#include <sstream>

void foo(std::stream &str) {
 str << "42\n";
};

int main() {
 int aNumber;
 std::stringstream aStringStream;
 foo(aStringStream); //Pass our stream to the function. It contains
    //"42\n" when the function returns.
 aStringStream >> aNumber; //aNumber == 42
 aNumber += 10; //aNumber == 52;
 std::cout << aNumber; //Print "52"
}

关于c++ - C++新手: Passing an fstream to a function to read data,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2581493/

10-12 07:32