gpt4 book ai didi

c++ - 我如何在 C++ 中将数字读入输出文件

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:46 36 4
gpt4 key购买 nike

如何从输入文件中获取数字以用于输出文件?

例如,假设我想读取 infile 中的数字并使用这些数字在 outfile 中显示为学生 ID。

最佳答案

这在一定程度上取决于您如何编写这些值。

显然你需要打开文件。
如果您使用 outfile << data 读取数据,您可能会使用 infile >> data 读取它。

如果您使用 fprintf() ,您可能会使用 fscanf() 阅读它,但不一定。

首先,您可以向我们展示您是如何编写输出文件的,然后快速尝试一下您如何阅读它并向我们展示它。然后我们可以给你一些关于如何进行的指导。

祝你好运!

更新
你似乎迷路了。我已经编写了一个简短的程序来完成您需要的一些事情,但我没有包含任何注释,因此您需要阅读代码。看看你是否能弄清楚你需要什么。

#include <iostream>
#include <fstream>
#include <string>


bool WriteNums(const std::string &sFileName, int nVal, double dVal)
{
std::ofstream ofstr(sFileName);
if (!ofstr.is_open())
{
std::cerr << "Open output file failed\n";
return false;
}
ofstr << nVal << " " << dVal;
if (ofstr.fail())
{
std::cerr << "Write to file failed\n";
return false;
}
return true;
}

bool ReadNums(const std::string &sFileName, int &nVal, double &dVal)
{
std::ifstream ifstr(sFileName);
if (!ifstr.is_open())
{
std::cerr << "Open input file failed\n";
return false;
}
ifstr >> nVal >> dVal;
if (ifstr.fail())
{
std::cerr << "Read from file failed\n";
return false;
}
return true;
}

int main()
{
const std::string sFileName("MyStyff.txt");
if(WriteNums(sFileName, 42, 1.23456))
{
int nVal(0);
double dVal(0.0);

if (ReadNums(sFileName, nVal, dVal))
{
std::cout << "I read back " << nVal << " and " << dVal << "\n";
}
}
return 0;
}

关于c++ - 我如何在 C++ 中将数字读入输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5652599/

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