gpt4 book ai didi

c++ - 如何在不使用 C++ 变量的情况下读取文件并打印到控制台?

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:17 25 4
gpt4 key购买 nike

在我的代码中有

for (int i = 0; i < 5; i++) {
ranInts= rand();//generate a random integer, store in ranInts
cout << ranInts<< " ";//Print out ints
binaryFile.write(reinterpret_cast <char *>(&ranInts), sizeof(int))//Write to file
}

要阅读的代码是

binaryFile.seekg(ios::beg);//Set the pointer in file to beginning
for (int i = 0; i < 5; i++) {
binaryFile.read(reinterpret_cast <char *>(&ranInts), sizeof(int));
//reading each int moves the file pointer down 4 bytes, ready to get the next one

//display
cout << ranInts<< endl;
}

这很好用。我想要做的是从磁盘转到屏幕并将变量留在循环之外。

这可能吗?

最佳答案

是的,这是可能的。调用 std::copy 将基于你的文件的 std::istream_iterator 复制到基于 cout< 的 std::ostream_iterator/:

std::ifstream file("myinput.txt");  // Open your input file
file.unsetf(std::ios_base::skipws); // Make sure whitespace is not skipped
std::copy( // Call std:copy to copy the content
std::istream_iterator<char>(file)
, std::istream_iterator<char>()
, std::ostream_iterator<char>(std::cout, "")
);

关于c++ - 如何在不使用 C++ 变量的情况下读取文件并打印到控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com