Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

checking if a string has certain characters 2

Status
Not open for further replies.

chineerat

Technical User
Oct 12, 2003
42
TT
hello their

i have a string and i want to check if it has only the following characters

MCDLXVI

if anythings else is present (including a space)an error message is displayed.
i've tried the following but it doesn't work

Code:
for( int n = roman.size()-1 ; n>= 1 ; n -- ){
if (roman[n]!= 'M' && roman[n]!= 'C' && roman[n]!= 'D' && roman[n]!= 'L' &&
    roman[n]!= 'X' && roman[n]!= 'V' && roman[n]!= 'I'){

cout<<"not a roman numeral"<<endl;

}


}

thanks in advance!!!!
 
Not really C++ but try this
Code:
#include <cstring>  // or #include <string.h>
...
if (strspn (roman.c_str(), "IVXLCDM") == roman.size ())
   // OK
else
   // not ok
 
I'd probably use the C version since it's a lot shorter, but here is the C++ version:
Code:
#include <string>
#include <iostream>
#include <algorithm>

using namespace std;

class pred
{
public:
	pred()
	:	m_Roman( "MCDLXVI" )
	{}

	template <class T>
	bool operator()( const T&  c )
	{
		return (m_Roman.find( c ) != string::npos);
	}

private:
	string	m_Roman;
};


bool IsRoman( const string&  str )
{
	return (static_cast<size_t>(count_if( str.begin(), str.end(), pred() )) == str.length());
}


int main()
{
	string str1( "MMDLXXVIMLDVI" );
	string str2( "MSLDFVTIM" );

	if ( IsRoman( str1 ) == false )
	{
		cout << endl << "str1 contains non-Roman numeral characters!" << endl;
	}

	if ( IsRoman( str2 ) == false )
	{
		cout << endl << "str2 contains non-Roman numeral characters!" << endl;
	}

	return 0;
}
 
See also find_first_not_of member function:
Code:
if (roman.find_first_not_of(latins) != string::npos)
{
// It's not a Roman numeral...
}
Go straight on, keep it simple (and effective;)...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top