Convert a series of digits into numbers

I am supposed to read data from a file ( the data below):
$1,9,5,6#%34,9
!4.23#$4,983

and convert them into digits and write the output to a file.

The tricky part is, each line of input could have several numbers separated by #. $1,9,56#%34,9 has two numbers on a line. The numbers would be 1956 and 349.

So with the data above, my output file should end up like this:

1956
349
423
4983

Each number should be on a separate line.


Here is what I have so far:


#include <fstream>
#include <iostream>
#include <cctype>
using namespace std;

int main()
{
ifstream data;
ofstream out;
char ch;
int n, sum;

data.open("Program1.txt");
if (!data)
{
cout << "Can't open Program1.txt" << endl;
system ("pause");
return 1;
}

out.open("Output.txt");
if (!out)
{
cout << "Can't open Output.txt" << endl;
system ("pause");
return 1;
}

data.get(ch);
while (data)
{
sum = 0;
while((ch != '\n') && data)
{
if(isdigit(ch))
{
sum = sum * 10;
sum = ch - 0;
}
//test for #
if((ch == '#') && data)
{
out.put(ch);
}
data.get(ch);
} // inner loop
if ( sum > 0) // test the sum
{
out.put(ch);
}
} // outer loop
system ("pause");
data.close(); out.close();
return 0;
}

Why will this not work?!
Program is invalid for example due to the following code

1
2
3
4
5
if(isdigit(ch))
 {
 sum = sum * 10;
 sum = ch - 0;
 }


The prervious value of sum equal to the evaluated expression sum * 10 is being overwritten by sum = ch - 0. Moreover there is no any sense in expression ch - 0 because it will always be equal to ch. I think you meant ch - '\0'.

As for me I would use getline instead of get and then sequentially search the first digit symbol and next symbol '#' and extract the number.
Last edited on
Well, let assume that string s contains "$1,9,5,6#%34,9". Then you can create a new string that will contain only digits and new line characters


1
2
3
4
5
6
7
8
9
10
11
12
std::string s( "$1,9,5,6#%34,9" );
std::string t;

s += '#';

for ( std::string::size_type i = 0; i < s.size(); i++ )
{
   if ( std::isdigit( s[i] ) ) t += s[i];
   else if ( s[i] == '#' ) t += '\n';
}

std::cout << t;


That is all you need.
Last edited on
Topic archived. No new replies allowed.