2013-10-31 71 views
1

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


} 

回答

3

您不应该使用char进行提取。如果要提取的值大于1个字节会怎样?另外,std::noskipws变为off跳过空格,实际上很难提取空格分隔的数字列表。如果空白字符是有效的字符以提取,则仅使用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

+0

好的,谢谢你。当我运行程序时,输入输入文件的名称,所需输出文件的名称。然后它结束。我去看看输出文件,它根本没有任何内容。所以即时通讯仍然不知道该程序有什么问题。有任何想法吗? – user2917900

+0

@ user2917900您是否收到任何错误?让我寻找更多的问题。 – 0x499602D2

+0

即时通讯使用Visual Studio 2012.我没有收到任何错误。我正在运行我上面的程序,并进行了更正。我输入我在该文件中随机生成的一些正数和负数的输入文件名,然后输入所需的输出文件名。然后,该输出文件中没有任何内容(当输入文件应该有正数时)。 – user2917900