从文件中流式传输数字
Streaming numbers from a file
我希望有人可以帮助我解决我在这里遇到的问题。我的程序在下面,我遇到的问题是我无法弄清楚如何编写 process() 函数来获取带有一堆随机数的 .txt 文件,读取数字,并仅将正数输出到单独的文件中。我已经被困在这个上面好几天了,我不知道还能去哪里求助。如果有人能提供任何形式的帮助,我将不胜感激,谢谢。
/*
10/29/13
Problem: Write a program which reads a stream of numbers from a file, and writes only the positive ones to a second file. The user enters the names of the input and output files. Use a function named process which is passed the two opened streams, and reads the numbers one at a time, writing only the positive ones to the output.
*/
#include <iostream>
#include <fstream>
using namespace std;
void process(ifstream & in, ofstream & out);
int main(){
char inName[200], outName[200];
cout << "Enter name including path for the input file: ";
cin.getline(inName, 200);
cout << "Enter name and path for output file: ";
cin.getline(outName, 200);
ifstream in(inName);
in.open(inName);
if(!in.is_open()){ //if NOT in is open, something went wrong
cout << "ERROR: failed to open " << inName << " for input" << endl;
exit(-1); // stop the program since there is a problem
}
ofstream out(outName);
out.open(outName);
if(!out.is_open()){ // same error checking as above.
cout << "ERROR: failed to open " << outName << " for outpt" << endl;
exit(-1);
}
process(in, out); //call function and send filename
in.close();
out.close();
return 0;
}
void process(ifstream & in, ofstream & out){
char c;
while (in >> noskipws >> c){
if(c > 0){
out << c;
}
}
//This is what the function should be doing:
//check if files are open
// if false , exit
// getline data until end of file
// Find which numbers in the input file are positive
//print to out file
//exit
}
您不应该使用 char
进行提取。如果要提取的值大于 1 个字节怎么办?此外,std::noskipws
关闭了空格的跳过,有效地使提取空格分隔的数字列表变得困难。如果空格字符是要提取的有效字符,请仅std::noskipws
使用,否则让文件流完成其工作。
如果您非常了解标准库,则可以使用通用算法(如std::remove_copy_if
)来接受如下所示的迭代器:
void process(std::ifstream& in, std::ofstream& out)
{
std::remove_copy_if(std::istream_iterator<int>(in),
std::istream_iterator<int>(),
std::ostream_iterator<int>(out, " "),
[] (int x) { return x % 2 != 0; });
}
这需要使用 C++11。将-std=c++11
选项添加到程序或升级编译器。
如果您不能使用这些方法,则至少在提取过程中使用int
:
int i;
while (in >> i)
{
if (i % 2 == 0)
out << i;
}
您在评论中说您需要使用getline
.这是错误的。我在这里假设您有多行空格分隔的整数。如果是这种情况,则不需要getline
。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- Angelscript从C++传输数组
- 我想将四个字节合并为一个数字以进行串行传输
- 为什么当我将 tolower() 的结果流式传输到 std::cout 时我会得到一个数字,而当我使用 putchar(
- 为什么 std::setprecision(6) 在固定宽度模式式传输超过 6 位数字
- 从文件中流式传输数字
- 输出以流式传输精确的浮点数字