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
}
好的,謝謝你。當我運行程序時,輸入輸入文件的名稱,所需輸出文件的名稱。然後它結束。我去看看輸出文件,它根本沒有任何內容。所以即時通訊仍然不知道該程序有什麼問題。有任何想法嗎? – user2917900
@ user2917900您是否收到任何錯誤?讓我尋找更多的問題。 – 0x499602D2
即時通訊使用Visual Studio 2012.我沒有收到任何錯誤。我正在運行我上面的程序,並進行了更正。我輸入我在該文件中隨機生成的一些正數和負數的輸入文件名,然後輸入所需的輸出文件名。然後,該輸出文件中沒有任何內容(當輸入文件應該有正數時)。 – user2917900