Instream & outstream | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Instream & outstream

So when you reading a file, char by char, how can you use a void function to remove all the white-space? How about at the start and at the end of the text. Purpose: remove white-space “Test1.dat” input file text “ Hello World 123 4567 “ “translated.dat” output file support to be “Hello World 123 4567” no space at begin and end #include <iostream> #include <fstream> using namespace std; void remove_blanks(ifstream& in_stream); int main() { const char INFILE[] = "test1.dat"; const char OUTFILE[] = "translated.dat"; char next; // get next char in file // setup input file stream fin.open(INFILE); if (fin.fail()) { cout << "Cannot open file\n"; exit(1); } // setup output file stream ofstream fout; fout.open(OUTFILE); if (fout.fail()) { cout << "Input file cannot be opened\n"; exit(1); } fin.get(next); while (! fin.eof()) { if (isspace(next)) { remove_blanks(fin); } fout.put(next); fin.get(next); } // end of file loop cout << "End of editing files.\n" << "Check translated.dat for result!" << endl; // close streams fin.close(); fout.close(); return 0; } void remove_blanks(ifstream& in_stream) { char symbol; in_stream.get(symbol); while (isspace(symbol)) { in_stream.get(symbol); } in_stream.putback(symbol); //error here it keep loop back to put back last char so file can’t end of file return;

15th Oct 2019, 2:56 AM
Phuc Hoang Trinh
Phuc Hoang Trinh - avatar
1 Answer
+ 1
I'm not well versed with I/o streams, but I'll try. I think in your function, you may be trying to rearrange the input stream (which might be a bad idea, because output streams is where the output goes). I think a simpler approach might do well. Test if the next char is a redundant space, if so, continue on. Else, put that char to the ofstream. To test it, it appears you allow only one space between words. You can set up a counter to keep track of the number of successive spaces found and reset it once it is > 1. You might not need to have a function after all, but having one that takes an ifstream and a ofstream (and an optional length requirement to specify when to stop) might be nice.
15th Oct 2019, 6:44 AM
Duck Typed
Duck Typed - avatar