In: Computer Science
Engineering problem solving with C++ by Delores Maria Etter Jeanine A. Ingber
Page 247
Question 15
Write a program that reads a file containing an integer and floating-point values separated by commas, which may or may not be followed by additional whitespace. Generate a new file that contains the integers and floating-point values separated only by spaces; remove all whitespace characters between the values, and insert a single space between the values. Do not change the number of values per line in the file.
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
// removing space from the string
string remSpaces(string str)
{
// remove all spaces
str.erase(remove(str.begin(), str.end(), ' '), str.end());
// return string
return str;
}
int main () {
// declaring variables
string line,str;
// declaring myoutfile object
ofstream myOutfile;
myOutfile.open ("output.txt");
ifstream myfile ("input.txt");
if (myfile.is_open())
{
// read line by line from the file
while ( getline (myfile,line) )
{
// calling removespaces function assaigning into string
str = remSpaces(line);
// replacing comma with spacces
replace(str.begin(), str.end(), ',', ' ');
// writing into file with new line character
myOutfile <<str<<"\n" ;
}
// closing both files
myfile.close();
myOutfile.close();
}
// if file is not found will give
else cout << "file not found";
return 0;
}