Data file of integers converted to Data file of integers without commas

Write a program that reads a file that only contains integers, but some of the integers have embedded commas, as in 145,020. The program should copy the information to a new file, removing any commas from the information. Do not change the number of values per line in the file.

Here is what I have so far. It works if there aren't any commas involved but I dont know how to make it work to take out the commas.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
ifstream fin;
ofstream fout;
int ivar, y;
string filename;
char junk;

cout << "Enter the name of the input file\n";
cin >> filename;

fin.open(filename.c_str());

if(fin.fail())
{
cerr << "Error opening the input file\n";
exit(1);
}

cout << "File" << filename << "is open." << endl;
cout << "Enter value" << endl;
cin >> y;

fout.open("outputfile.txt");

while(fout.fail())
{
cerr << "Error in opening the output file\n";
exit(-1);
}

cout << "output file is open" << endl;

while(!fin.eof())
{
fin >> ivar;
fout << ivar << endl;
}
fin.close();
fout.close();
}

int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}

Hi tomgreiner,

the problem is in the main loop:
1
2
3
4
5
while(!fin.eof())
{
    fin >> ivar;
    fout << ivar << endl;
}

(btw., please use the code-tag). The problem is, that "fin >> ivar" only reads integers in their standard form, i.e. without commas.

One way to solve this, is to read the input character by character (not: number by number), and put everything except commas directly to the output stream. As streams usually take care of buffering, this should not slow down your program to much (it should even give a speedup, as the integers do not need to be parsed).

Greetings, TheBear
Last edited on
Topic archived. No new replies allowed.