answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

How do you programme 1 232 34543 232 1 in C?

int main (void)

{

puts ("1 232 34543 232 1");

return 0;

} int main (void)
{ puts ("1 232 34543 232 1"); return 0; }

When is a function executed and where should a function prototype and function definition appear in a source program?

If you want to use prototype it has to be declared before main(). If you have a function of type double with one argument of type int (with name arg), and the function name is func, then we have:

#include

...

double func(int arg);

...

int main(...)

{

...

return 0;

}

...

double func(int arg)

{

...

}

What is file mode and list various file mode operations available?

A file mode describes how a file is to be used, to read, to write to append etc. When you associate a stream with a file, either by initializing a file stream object with a file name or by using open() method, you can provide a second argument specifying the file mode.

e.g. stream_object.open("filename",filemode);

Following is the list of filemodes available in C++

ios::in

ios::out

ios::binary

ios::ate

ios::app

ios::trunc

ios::nocreate

ios::noreplace

What is the function and purpose of cinema?

I've written a Blog about the same topic in relation to some events in my country: http://srijanfoundation.wordpress.com/2007/11/02/chak-de-india-the-non-message/.

Love,

Rahul Dewan

--

http://srijanfoundation.wordpress.com/

http://srijantech.wordpress.com/

http://www.srijan.in

Which function reads character into an array specified bt its parameter in c plus plus?

void foo (char& c)

{

cin >> c;

}

int main()

{

char ch[10] {};

for (size_t c=0; c!=10; ++c)

foo (c[0]);

}

What is the difference between structures and class?

HedgingI have removed all but one answer while writing this. Please check my references to the c++ standard before removing this as vandalism; nearly every info bit on this page was incorrect or misunderstood to begin with. BackgroundThe question here regards specifically c++. This is not a cross-language question; neither struct nor class means the same thing from language to language, and c++ is the only language which has both in a way such that they are related (as well as its offshoots, such as concurrent c++.) This question is a common misunderstanding, though, for novice c++ programmers, and is frequently given in c++ faqs. Outside of c++, the answer is "those terms could mean anything." Primary answerThe fundamental issue is that of maintaining backwards compatability with C. When Bjarne created C++ (under the old name C with Classes) he wanted to emulate Smalltalk's object model in C. One of the important features Bjarne was adding to C++ was the concept of accessor privelege (private, public and protected.) When those things are added to a language, it is generally done such that private is the default.

In order for code from C to work with C++, the members of a structure would be expected to be public. However, Bjarne knew that default privacy was important. The solution chosen was to clone the "struct" keyword and make this one small change. In fact structs and classes are the same thing; you can inherit structs from classes and vice versa (though it's pretty stupid, it's legal.) The ONLY technical difference between structs and classes is whether members default to private or public accessorship. This can be derived from the language of section 3.1 of the C++ standard (ISO IEC 14882-1998.)

Repeat with me: "The only difference in C++ between struct and class is that struct is default public, whereas class is default private."

Extra informationSeveral misunderstandings were in place here. I will explain them one by one, so that their removal is not protested. Value and Reference Typing"''structures are value typed where as classes are refernce typed''"'''Incorrect'''. This was the case in Microsoft Visual C++ 5 and 6. The problem is that MSVC5 and 6 are older than C++; they implemented speculative versions of the language before the standard came out. Both have quite a few errors which were good guesses but didn't pan out; this is one of them. An easier example is:

for (int i=0; i<10; ++i) {} int i;

The compiler will incorrectly flag that as a redeclaration and fail.

Inheritance"''Class can be inherited But Structure can't be inherited''"'''False''', and easily tested.

#include

struct base {

public: virtual int foo() { return 5; }

};

struct child {

public: int foo() { return 9; }

};

int main() { base* example = new child; std::cout << child.foo(); }

Initialization"''In structures we cannot initilase the variable during the declaration while in classes we can.''"'''False'''. You may tuple initialize any structure or class which is pure POD, and you may not tuple initialize any structure or class which contains methods. However, you may initialize structures or classes with methods in their constructor instead. Anonymous Classes and Anonymous Structures"''Structure can be declared without a tag at the first time, but not in case of class.''"'''Wrong'''. The fault is in the example code. Old code:

struct { int something; } sFoo;

sFoo sfoo; // works fine

class { int something; } cFoo;

cFoo cfoo; // error: cannot instantiate

The problem is not about classes and structures; it's about default publicity. Structures are default public and classes are default private. When declared in that fashion, since there is no explicit constructor, a constructor is generated by the compiler for each. The constructor for the structure is default public, so the structure constructs just fine. However, the constructor for the class is default private, meaning that at instantiation time, the programmer does not have the access privelege to construct it. The error that results in most compilers talks about being unable to instantiate the class, and that can easily be misunderstood as a code bug, when in fact it's a usage bug.

Polymorphism"''Structure s does not support polymorphism while class does.''"Simply '''false''', and a common and often repeated misunderstanding. The test for inheritance above also happens to display polymorphism. POD versus UDT"''A structure is an entity that is defined in terms of other structures or primitive datatypes. As a result, a structure is normally considered to be a complex-, or compound datatype. With structures the default access type is public. Classes are similar to structures in that they are made up of other datatypes, but they differ in one significant respect - classes contain information on the program functions (formally termed "methods") that will be used to manipulate the data that the class can store. The default access type for classes is private.''"'''This is a more complex issue'''. Whereas this is generally the case in code, that's by convention; the language makes no such requirement. In fact the author of this comment even tips his hat to that structures may have methods later, but the phrasing here suggests that this is part of c++, whereas in fact it is not. More clearly put, there is the concept of a "POD type." POD, or Plain Old Data, is any type which consists solely of inert storage - pointers, integers, arrays, that sort of thing. The alternative is called a UDT, or user-defined type; whereas most POD is user defined and whereas most POD is typal, what a user-defined type is meant to mean is a type which has user-defined behavior, ie something other than what the hardware does. Good examples are arithmetic number classes (a class which stores a numerator and a denominator, instead of the real value, so that there is no loss of precision) and many instances of the C++ string class, which frequently implement such things as shared buffers and lazy copies. The fundamental issue here is that most C++ programmers use the struct keyword to make POD and the class keyword to make everything else, and the behavior is so common that it's important to know it; however it's also important to realize that that's an idiom, not a language requirement, because sometimes POD should have methods like copy constructors, such as when copying the data requires things that aren't usually handled, like copying a word at a time over a limited-range bus. AnswerIn structure,the default access specifier is public,where in class the default access specifier is private.

How do you describe the importance of destructors?

Destructors are used to free memory and release resources.

Give an example of how getchar function is used in C program.?

The getchar() function is used to read a single character from standard input (stdin) and increment the associated file pointer to point to the next character. The return value is an integer which must be cast to a character.

An example demonstrating its usage is shown below.

#include <stdio.h>

int main()

{

char buffer[81];

int i, ch;

for(i=0; (i<80) && ((ch = getchar()) != EOF) && (ch!='\n'); ++i)

{

buffer[i] = (char) ch; // cast input to a character

}

buffer[i] = '\0'; // add null-terminator.

printf( "You entered: %s\n", buffer);

}

Describe about storage allocation and scope of global extern static local and register variables?

Global Varible:

The variable which is declared as "Global" one : having the preveleges to use and access that variable in any class and object( means any where in the program) just like PUBLIC keyword in OOPS concepts.

Static Variable :

If we declare a variable as Static , then it wont have the permission to access that variable through out the program and u have to use it inside the class or object which u declared itself.

All the Best

Annapurna

Is Visual C plus plus a good Game Development Language?

Hmm...
Visual C++ isn't really a language, it's more like an environment in which you can create programs using different tools.
Anyway, C++ is the best language you can learn if you want to get started as a game programmer. It's the most efficient and it's probably gonna stay that way. Hope that helped.


Rocamora

What is called Dividing a program into function and modules?

Modularisation. It could also be called refactoring, where large and complex functions are split into several simpler functions, making code easier to read. Refactoring can also help to reduce code duplication.

What is the difference between default constructor and parameterized constructor?

A default constructor is one that has no parameters (C++ also calls constructors with all default parameters a default constructor), while a parameterized constructor is one that has at least one parameter without a default value. Default constructors can be provided by the compiler if no other constructors are defined for that class or any class the class inherits from, while parameterized constructors must always be defined by the developer.

How do you invoke the constructor function in c plus plus?

There is no such thing as a constructor function in C++ (constructors have no return value, not even void, and cannot be called like regular functions). Constructors are invoked rather than called directly, either by declaring a static variable of the class type, or via the C++ new operator.

What is the difference between subscript and subscripted variable in c plus plus?

Subscripts are used to identify the elements in an array, where the first element has subscript 0. Thus an array of n elements has subscripts in the range 0 to n-1. Each element may itself be an array, thus allowing multi-dimensional arrays.

The subscript may be a constant or a variable. However, when declaring a static array, the subscript must be a constant. Constants include literal constants as well as named constants.

A subscripted variable is simply an array or a datatype that can be divided into an array. For instance, a 32-bit int can be treated just as if it were an array of two 16-bit shorts or four 1-byte chars.

Thus in the 32-bit int array, int i[10], i is a subscripted variable where i[0] is the first integer and i[9] is the last. If we then say char*c=&i, c would allow us to treat i as if it were a subscripted variable with 40 char elements (c[0] to c[39]).

How do you use copy-paste in c and c plus plus program?

Copy/paste is facilitated by the operating system clipboard. This answer discusses the Windows operating system clipboard only. For other operating systems, consult the application programming interface (API) documentation related to that operating system.

Except for registering clipboard formats, individual windows perform most clipboard operations. A window procedure transfers information to or from the clipboard in response to the WM_COMMAND message.

The four conventional copy/paste commands are:

  • Cut : places a copy of the current selection on the clipboard and deletes the selection from the document. The previous clipboard content is destroyed.
  • Copy : command places a copy of the current selection on the clipboard. The previous clipboard content is destroyed.
  • Paste : replaces the current selection with the clipboard content. The clipboard content remains unchanged.
  • Delete : deletes the current selection from the document. The clipboard content remains unchanged.

These commands are conventionally provided via the window's context-sensitive Edit command menu, however they should also be mapped to the conventional keyboard accelerators: CTRL+X (cut), CTRL+C (copy), CTRL+V (paste) and DEL (delete).

[The Print Screen accelerator is usually mapped to the shell program (explorer.exe, by default). This accelerator is typically used to take a snapshot of the current desktop (ALT+Print Screen takes a snapshot of the active window). The snapshot (a 1:1 bitmap image) is copied to the clipboard, replacing the current clipboard content.]

The clipboard owner is the window associated with the current information on the clipboard. A window becomes the owner when it places information on the clipboard -- specifically, when it invokes the EmptyClipboard function. The window remains the owner until the window is closed or another window empties the clipboard.

The EmptyClipboard function posts a WM_DESTROYCLIPBOARD message to the current clipboard owner and assigns ownership to the current window. Upon receiving a WM_DESTROYCLIPBOARD message, a clipboard owner must release all resources associated with the information it owns.

Once the clipboard is emptied, the new owner may place new information upon the clipboard. Information can be stored in one or more supported formats, including user-defined formats. The standard formats are:

CONSTANT (value): Description

CF_TEXT (1): Text format. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data. Use this format for ANSI text.

CF_BITMAP (2): A handle to a bitmap (HBITMAP).

CF_METAFILEPICT (3): Handle to a metafile picture format as defined by the METAFILEPICT structure. When passing a CF_METAFILEPICT handle by means of DDE, the application responsible for deleting hMem should also free the metafile referred to by the CF_METAFILEPICT handle.

CF_SYLK (4): Microsoft Symbolic Link (SYLK) format.

CF_DIF (5): Software Arts' Data Interchange Format.

CF_TIFF (6): Tagged-image file format.

CF_OEMTEXT (7): Text format containing characters in the OEM character set. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data.

CF_DIB (8): A memory object containing a BITMAPINFO structure followed by the bitmap bits.

CF_PALETTE (9): Handle to a colour palette. Whenever an application places data in the clipboard that depends on or assumes a colour palette, it should place the palette on the clipboard as well. If the clipboard contains data in the CF_PALETTE(logical colour palette) format, the application should use the SelectPalette and RealizePalette functions to realise (compare) any other data in the clipboard against that logical palette. When displaying clipboard data, the clipboard always uses as its current palette any object on the clipboard that is in the CF_PALETTE format.

CF_PENDATA (10): Data for the pen extensions to the Microsoft Windows for Pen Computing.

CF_RIFF (11): Represents audio data more complex than can be represented in a CF_WAVE standard wave format.

CF_WAVE (12): Represents audio data in one of the standard wave formats, such as 11 kHz or 22 kHz

PCM.

CF_ENHMETAFILE (14): A handle to an enhanced metafile (HENHMETAFILE).

CF_UNICODETEXT (13): Unicode text format. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data.

CF_HDROP (15): A handle to type HDROP that identifies a list of files. An application can retrieve information about the files by passing the handle to the DragQueryFilefunction.

CF_LOCALE (16): The data is a handle to the locale identifier associated with text in the clipboard. When you close the clipboard, if it contains CF_TEXT data but no CF_LOCALE data, the system automatically sets the CF_LOCALE format to the current input language. You can use the CF_LOCALE format to associate a different locale with the clipboard text. An application that pastes text from the clipboard can retrieve this format to determine which character set was used to generate the text. Note that the clipboard does not support plain text in multiple character sets. To achieve this, use a formatted text data type such as RTF instead. The system uses the code page associated with CF_LOCALE to implicitly convert from CF_TEXT to CF_UNICODETEXT. Therefore, the correct code page table is used for the conversion.

CF_DIBV5 (17): A memory object containing a BITMAPV5HEADER structure followed by the bitmap colour space information and the bitmap bits.

CF_OWNERDISPLAY (0x0080): Owner-display format. The clipboard owner must display and update the clipboard viewer window, and receive the WM_ASKCBFORMATNAME, WM_HSCROLLCLIPBOARD, WM_PAINTCLIPBOARD, WM_SIZECLIPBOARD, and WM_VSCROLLCLIPBOARD messages. The hMem parameter must be NULL.

CF_DSPTEXT (0x0081): Text display format associated with a private format. The hMem parameter must be a handle to data that can be displayed in text format in lieu of the privately formatted data.

CF_DSPBITMAP (0x0082): Bitmap display format associated with a private format. The hMem parameter must be a handle to data that can be displayed in bitmap format in lieu of the privately formatted data.

CF_DSPMETAFILEPICT (0x0083): Metafile-picture display format associated with a private format. The hMem parameter must be a handle to data that can be displayed in metafile-picture format in lieu of the privately formatted data.

CF_DSPENHMETAFILE (0x008E): Enhanced metafile display format associated with a private format. The hMem parameter must be a handle to data that can be displayed in enhanced metafile format in lieu of the privately formatted data.

CF_PRIVATEFIRST (0x0200): Start of a range of integer values for private clipboard formats. The range ends with CF_PRIVATELAST. Handles associated with private clipboard formats are not freed automatically; the clipboard owner must free such handles, typically in response to the WM_DESTROYCLIPBOARD message.

CF_PRIVATELAST (0x02FF): See CF_PRIVATEFIRST.

CF_GDIOBJFIRST (0x0300): Start of a range of integer values for application-defined GDI object clipboard formats. The end of the range is CF_GDIOBJLAST. Handles associated with clipboard formats in this range are not automatically deleted using the GlobalFree function when the clipboard is emptied. Also, when using values in this range, the hMem parameter is not a handle to a GDI object, but is a handle allocated by the GlobalAlloc function with the GMEM_MOVEABLE flag.

CF_GDIOBJLAST (0x03FF): See CF_GDIOBJFIRST.

For more information, consult the Windows Dev Centre. Search for "Clipboard".

Why you use integer variables when the value of float and integer is same?

Integers are always guaranteed to be precise, provided you have sufficient bits to represent the number (plus the sign, if required). All logical and mathematical operations are extremely efficient when working with integers, even with division which simply truncates any fraction. If that's all the precision you need then you don't need to use a float. But if you need real numbers, then you must use a float.

Floating point numbers are never guaranteed to be accurate. Irrational numbers (such as pi and 1/3) are impossible to represent fully within a finite number of bits, thus there has to be a degree of precision. All floating point numbers are actually represented in computer memory using the binary equivalent of scientific notation, so even when dealing with small integer values, logic errors can creep in (such as 0.9 + 0.1 == 1.000000...01). Thus when working with floats you have to accommodate for the degree of precision.

Due to the increased complexity of floating point numbers, they are much less efficient than when working solely with integers. Thus if you can guarantee that a floating point number can be accurately represented as an integer (no fractions), then it makes more sense to use an integer. However, if you cannot make that guarantee then you must use a float.

Integer division can be problematic due to truncation, so it's often necessary to cast integers to floats to obtain a higher degree of precision, rounding the result as appropriate before casting back to an integer. Repeatedly converting back and forth can be costly, so it's sometimes better to just work with a float from the outset.

C plus plus program to store first 10 prime numbers in an array?

#include <iostream>

bool isPrime(int p)

{ if( p<=1 ( p>2 && p%2==0 ))return( false );int max = (int)sqrt(( double ) p ) + 1;for( int i=3; i<=max; i+=2 )if( p%i==0 )return( false );return( true );

}

int main()

{ int primes[10];

int count=0, num=0;

while( count!= 10 )

{num+=num>2?2:1;if( isPrime(num) )primes[count++]=num;}for( int i=0; i<10; ++i )std::cout << primes[i] << std::endl;return( 0 );

}

What subjects are needed to update c plus plus?

You don't need any "subjects" (whatever that means). Simply read the documentation that came with the update.

What actually happens when function get called how the compiler is reading the next instruction after completing that function?

When a function gets called, the processor first stores the address of the calling function in a structure called activisation structure and jumps to the called function. Then it allocates the memory for the local variables and initializes them. Then it does the processing in that function. After that it deallocates the memory allocated for the local variables and returns to the calling function. When a function gets called, the processor first stores the address of the calling function in a structure called activisation structure and jumps to the called function. Then it allocates the memory for the local variables and initializes them. Then it does the processing in that function. After that it deallocates the memory allocated for the local variables and returns to the calling function.

How do you convert from Decimal to base6 in c plus plus code?

The following code will convert any number in any base to any other base, from binary to hexadecimal, and everything inbetween.

#include<iostream>

#include<string>

#include<sstream>

typedef unsigned long long ull;

typedef unsigned long ul;

const std::string symbols="0123456789abcdef";

std::string inputvalue(ul base)

{

using namespace std;

string value;

while(1)

{

cout<<"Enter a positive value : ";

string s;

getline(cin,s);

if(s.size())

{

for(string::iterator i=s.begin();i!=s.end();++i)

if(*i>='A' && *i<='Z')

*i+=32;

string actual = symbols.substr(0,base);

if(s.find_first_not_of(actual)!=string::npos)

{

cout<<"The value you entered is invalid for the base.\n"

<<"Please enter another value.\n"<<endl;

continue;

}

value=s;

break;

}

}

return(value);

}

ul inputbase(std::string prompt)

{

using namespace std;

ul result=0, min=2, max=16;

while(1)

{

cout<<prompt.c_str()<<" ["<<min<<".."<<max<<"] : ";

string s;

getline(cin,s);

if(s.size())

result=stoul(s,0,10);

if(result<min result>max)

cout<<"The base must be in the range "

<<min<<".."<<max<<"\n"

<<"Please enter another base.\n"<<endl;

else

break;

}

return(result);

}

ull base2dec(std::string value,ul base)

{

ull col=1, num=0;

for(std::string::reverse_iterator i=value.rbegin(); i!=value.rend(); ++i)

{

num+=symbols.find(*i,0)*col;

col*=base;

}

return(num);

}

std::string dec2base(ull dec,ul base)

{

using namespace std;

int len=1;

ull tmp=dec;

while(tmp/=base)

++len;

string value("0",len);

while(dec)

{

value[--len]=symbols[dec%base];

dec/=base;

}

return(value);

}

int main()

{

using namespace std;

ul base=inputbase("Enter the base of the value");

string value=inputvalue(base);

ul newbase=inputbase("Enter the base to convert to");

value=dec2base(base2dec(value,base),newbase);

cout<<"New value:\t"<<value.c_str()<<endl;

return(0);

}

How do you modify properties of other forms during run time in C plus plus?

By "other forms" I presume you mean forms outside of your application. The only way to modify their properties is via the interface provided by those forms. You also need to be aware that those forms can fall from scope at any time.

Create a class IntStr that stores a positive decimal integer as a string the maximum number of decimal digits in the string can be assumed to be only 5 digits so the maximum value that can be stored?

Am not sure it is a good idea to embed the integer as a string. Aside from the inefficiency of storing a 5-digit number as a string, what would be the expected result of adding two IntStr objects together? E.g., "40" + "2" could either be "42" (add), or "402" (append) depending on your intentions. And if you wished to add an IntStr and an integer, such as "40" + 2, then you'd have to convert the embedded string back to an int, perform the addition, and if the sum is less than 100000, then convert the sum back to a string. This is highly inefficient. Personally, I'd embed the integer itself and provide accessors and casts to explicitly convert it to a string on an as-required basis only, since the numeric form is likely to be far more useful to you than the string form.

However, to answer the question as it stands, the following is one possible solution.

#include<iostream>

#include<string>

#include<sstream>

class IntStr

{

private:

std::string m_string;

public:

IntStr():m_string("0") {}

IntStr(const unsigned int decimal):m_string("0")

{

set_int(decimal);

}

IntStr& operator=( const unsigned int decimal )

{

return( set_int( decimal ));

}

std::string get_int()const{ return(m_string); }

IntStr& set_int(const unsigned int decimal)

{

if( decimal<100000 )

{

std::stringstream ss;

ss<<decimal;

m_string = ss.str();

}

return( *this );

}

};

int main()

{

IntStr a; // default constructor.

a = 42; // assignment operator.

IntStr b = a; // copy constructor.

IntStr c(1000); // user-defined constructor.

IntStr d(100000); // overflow check.

std::cout<<"a = "<<a.get_int().c_str()<<std::endl;

std::cout<<"b = "<<b.get_int().c_str()<<std::endl;

std::cout<<"c = "<<c.get_int().c_str()<<std::endl;

std::cout<<"d = "<<d.get_int().c_str()<<std::endl;

}

Example output:

a = 42

b = 42

c = 1000

d = 0

How do you include mysql.h file to vc plus plus?

To include mysql.h you must first locate the mysql header file and its associated libmysql library file and DLL. If you don't have them, you must download them from the MySQL website, on the Downlads (GA) page (GA = generally available). Download and save the Windows version which includes everything (around 208MB). Once downloaded, proceed with the installation of MySQL. Choose the Developer Default, Full installation, or customise what you need.

To include mysql.h, you must specify the path to the file in Project Properties (ALT+F7) in the VC++ Directories > Include Directories. By default, this file resides in "<program files>\MySQL\Connector C 6.0.2\include". Do this for all configuration types (debug, release, etc) and for all projects that require MySQL.

Thereafter you can include mysql.h in any file that requires it:

#include <mysql.h>

You must also link with the appropriate library files. They can be found in "<program files>\MySQL\Connector C 6.0.2\lib", with separate folders for the debug and optimised (release) versions of each. Specify the appropriate folder in your Project Properties > VC++ Directories > Library Directories for each build type.

Finally, specify the required libraries in the Project Properties > Linker > Input > Additional Dependencies.

Note that prior to VS2010, include and library directories are assigned globally rather than per project, per build type. For earlier versions, look in Tools > Options > Projects and Solutions > VC++ Directories instead. For the library, you must include the lib folder only (not the debug or opt folders). And in the Project Properties, you must include the appropriate debug or opt path in your linker's Additional Dependencies (e.g., debug\libmysql.lib for debug builds and opt\libmysql.lib for release builds).

How do you convert a decimal into a BCD in C plus plus?

The following program shows one way to convert to BCD using a variation of packed BCD 8421 encoding. Each digit is represented by 4 bits in the range 0x0 to 0x9. 0xa denotes a minus symbol (for negative values) while 0xb denotes a decimal point for floating point values. The unused value 0xf is used to pad a BCD to a full byte when the number of symbols is odd. Values 0xc, 0xd and 0xe are ignored, but could be used for other purposes such as when representing exponents or fractions/ratios.

Values may be any length, the BCD being represented by a vector of type unsigned char. Since the value of a BCD could easily exceed the range of a long double or a 64-bit integer, conversion to these types is disabled. BCD values are constructed from an input string and converted back to a string for output.

Arithmetic operations can be overloaded to handle a BCD (using decimal notation arithmetic), however this has been left as an exercise for the reader.

#include<iostream>

#include<sstream>

#include<vector>

#include<exception>

using uchar = unsigned char;

class BCD_8421

{

private:

std::vector<uchar> v;

static const uchar lo_mask {0x0f};

static const uchar hi_mask {0xf0};

public:

BCD_8421 (void);

BCD_8421 (const BCD_8421&);

BCD_8421 (BCD_8421&&);

BCD_8421 (const std::string&);

BCD_8421& operator= (const BCD_8421&);

BCD_8421& operator= (BCD_8421&&);

BCD_8421& operator= (const std::string&);

static bool is_valid (const std::string& s);

operator std::string (void) const;

friend std::ostream& operator<< (std::ostream&, const BCD_8421&);

};

BCD_8421::BCD_8421 (void): v(1, 0) {}

BCD_8421::BCD_8421 (const BCD_8421& bcd): v (bcd.v) {}

BCD_8421::BCD_8421 (BCD_8421&& bcd): v (std::move(bcd.v)) {}

BCD_8421::BCD_8421 (const std::string& s): v{} { *this = s; }

BCD_8421& BCD_8421::operator= (const BCD_8421& bcd) { v=bcd.v; return *this; }

BCD_8421& BCD_8421::operator= (BCD_8421&& bcd) { v=std::move(bcd.v); return *this; }

BCD_8421& BCD_8421::operator= (const std::string& s)

{

v.clear();

uchar c {};

bool msb {false};

bool minus {false};

bool point {false};

bool error {false};

bool digit {false};

for (auto i=s.begin(); i!=s.end(); ++i)

{

if (!msb)

c = hi_mask;

uchar x;

switch (*i)

{

case ('0'):

if (!digit)

continue;

case ('1'):

case ('2'):

case ('3'):

case ('4'):

case ('5'):

case ('6'):

case ('7'):

case ('8'):

case ('9'):

digit = true;

x = *i - '0';

break;

case ('.'):

if (!point)

{

point = !point;

x = 10;

break;

}

else

error = !error;

case ('-'):

if (!minus && i==s.begin())

{

minus = !minus;

x = 11;

break;

}

default:

error = !error;

}

if (error)

{

v.clear();

v.push_back (hi_mask);

std::stringstream ss;

ss << "Error: invalid argument in BCD_8421.operator= ("" << s << "")";

throw std::invalid_argument (ss.str());

}

if (msb)

v.push_back ((c & lo_mask) | (x << 4));

else

c |= x;

msb = !msb;

}

if (msb && c)

v.push_back (c);

else if (!digit)

{

v.clear();

v.push_back (hi_mask);

}

return *this;

}

bool BCD_8421::is_valid (const std::string& s)

{

const std::string valid_chars {"0123456789-."};

if (s.find_first_not_of (valid_chars) != valid_chars.npos)

return false;

auto f = s.find ('-');

if (f != s.rfind('-') (f && f!=s.npos))

return false;

if (s.find ('.') != s.rfind('.'))

return false;

return true;

}

BCD_8421::operator std::string (void) const

{

std::stringstream ss;

bool digit {false};

bool point {false};

for (auto i : v)

{

bool msb {false};

do

{

uchar c {};

uchar x = msb ? i >> 4 : i & lo_mask;

switch (x)

{

case (0x0):

case (0x1):

case (0x2):

case (0x3):

case (0x4):

case (0x5):

case (0x6):

case (0x7):

case (0x8):

case (0x9): c = '0' + x; digit = true; break;

case (0xa): c = '.'; point = true; break;

case (0xb): c = '-'; break;

default: break;

}

if (point && !digit)

ss << '0';

if (c) ss << c;

msb = !msb;

} while (msb);

}

if (ss.str().back()=='.')

ss << '0';

return ss.str();

}

std::ostream& operator<< (std::ostream& os, const BCD_8421& bcd)

{

return os << static_cast<std::string> (bcd);

}

int main()

{

for (unsigned loop=0; loop<10; ++loop)

{

std::string input;

while (true)

{

std::cout << "Enter a numeric value: ";

std::cin >> input;

if (BCD_8421::is_valid (input))

break;

std::cerr << "Invalid input.\n";

}

try

{

BCD_8421 a = input;

std::cout << "You entered the value: " << a << std::endl;

}

catch (std::range_error& e)

{

std::cerr << e.what() << std::endl;

}

}

}