从文件中流式传输数字



我希望有人可以帮助我解决我在这里遇到的问题。我的程序在下面,我遇到的问题是我无法弄清楚如何编写 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

相关内容

  • 没有找到相关文章

最新更新