如何在c++中将数字读入输出文件
file io - How do i read numbers into an outfile in C++
如何从文件中获取要在输出文件上使用的数字?
例如,假设我想读取inffile中的数字,并使用这些数字在outfile中显示为学生id。这取决于您如何编写这些值。
显然你需要打开文件。
如果您使用outfile << data
写入数据,那么您可能会使用infile >> data
读取数据。
如果您使用fprintf()
,您可能会使用fscanf()
来阅读它,尽管不一定。
首先,你给我们展示一下你是怎么写outfile的,然后快速尝试一下你是怎么读的,然后展示给我们看。然后我们可以给你一些指导如何进行。
祝你好运!
你好像迷路了。我编写了一个简短的程序,可以完成您需要的一些事情,但我没有包含任何注释,因此您需要阅读代码。看一看,看看你是否能找出你需要的东西。
#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 failedn";
return false;
}
ofstr << nVal << " " << dVal;
if (ofstr.fail())
{
std::cerr << "Write to file failedn";
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 failedn";
return false;
}
ifstr >> nVal >> dVal;
if (ifstr.fail())
{
std::cerr << "Read from file failedn";
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;
}
istream_iterator
和ostream_iterator
非常有趣。
查看您可以用它做的整洁的事情。下面是一个华氏到摄氏转换器的简单示例,它读取输入并产生输出:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
using namespace std;
typedef float input_type;
static const input_type factor = 5.0f / 9.0f;
struct f_to_c : public unary_function<input_type, input_type>
{
input_type operator()(const input_type x) const
{ return (x - 32) * factor; }
};
int main(int argc, char* argv[])
{
// F to C
transform(
istream_iterator<input_type>(cin),
istream_iterator<input_type>(),
ostream_iterator<input_type>(cout, "n"),
f_to_c()
);
return 0;
}
相关文章:
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- VI工作室代码错误无法打开输出文件主.exe
- 在代码块中查找输出文件
- 将未签名的字符写入输出文件
- 为什么我的代码不写入输出文件?
- 完成搜索任务时为空输出文件
- 如何将地图<列表<string>、矢量<string>>输出到输出文件?
- 无法在代码块 IDE 中打开输出文件.exe
- C++:更改 IF 语句中的输出文件
- 编译 gsoap 输出文件 (onvif) 时出现问题
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- while 循环中的流输出文件() 通常生成空文件
- 如何使用 Docker 访问输出文件
- 提升进程间共享内存删除、权限和输出文件
- 查找素数,然后将质数放入输出文件中
- GDB / C++ - 根据循环条件将多个变量记录到输出文件中
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 我的输出文件未显示解决方案
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- C++,我正在尝试创建一个有效的.bmp输出文件