Here is a 'shell' to get you started then ...
Hint: You could use the alpha to integer function call ...
atoi( nStr.substr(i,1).c_str() )
<Note: the .c_str() at the end coverts the C++ sub-string to a C string
that is required for the 'atoi( cStr)' function call ... the atoi(cStr) call
returns an 'int'>
to get a single integer digit from a string of digits in string 'nStr' at index 'i'
CODE
/*
Demo of converting DECIMAL NUMERALS to ROMAN NUMERALS ...
Modified for strings, and to use the MSD, (Most Significant Digit)
rather than the LSD (Least Significant Digit) method used by Randy.
Randall Hyde is the author of HLA (High Level Assembly) ... See ...
http://webster.cs.ucr.edu/AoA/index.html
http://developers-heaven.net/forum/index.php/topic,46.0.html
*/
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#define debugging true
using namespace std;
string convert( int n )
{
if( n > 3999 ) return "Largest number handled is 3999";
if( n < 1 ) return "Smallest number handled is 1";
string romanNum[] =
{ "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
char buffer[20];
itoa( n, buffer, 10 ); // convert integer to C string char's
string nStr = string(buffer); // convert C string to C++ string
string rm =""; // to hold the Roman Number
int msd;
for( int i=0; i<nStr.length(); ++i )
{
// Extract the NEXT Most Significant Digit (MSD)
// from the number 'n' ... as a string now, i.e. 'nStr'
// msd = ???? ...................................
// Here is the trick, (from Randy of HLA), that makes this work ...
// 'Multiply' the Roman Number by Ten. This is achieved by
// swapping the characters in the char string 's1' below
// with their corresponding character in char string 's2' below ...
char s1[] = "IVXLCDM";
char s2[] = "XLCDM**";
int j, k;
for( j=0; j< rm.length(); j++ )
{
for( k=0; k<7; k++ )
{
if( rm[j] == s1[k] )
{
rm[j] = s2[k];
break;
}
}
}
// Convert the current MSD to a string
// and append to the end of "rm".
rm = rm + romanNum[msd];
}
return rm;
}
void convertAndShow( int n )
{
cout << "The number " << n << " converted is " << convert(n) << endl;
}
int main()
{
// get file name and open that file to read numbers
// and validate that it was opened ok ...
ifstream myfile;
string filename;
// or for testing via keyboard input ...
#if debugging
goto testing;
#endif
do
{
cout << "Please enter filename: ";
myfile.clear();
cin >> filename;
cin.sync(); //eat any char's that cin may have missed in in-stream
myfile.open( filename.c_str() );
if( myfile.fail() )
cout << "File cannot be found" << endl;
}while( myfile.fail() );
int a;
while( myfile >> a )
convertAndShow( a );
myfile.close();
#if debugging
testing:
string message = "Enter number from the keyboard (q to quit) : ";
cout << message;
while( cin >> a ) { convertAndShow( a ); cout << message; }
cin.clear();
cin.sync();
#endif
cout << "\nPress 'Enter' to continue ... ";
cin.get();
}
This post has been edited by David W: 8 Oct, 2008 - 07:53 PM