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

What is a function and its types in C plus plus?

What is a function?

A function is a procedure call; a re-usable block of one or more statements that can be called from any code that has access to it. Unlike a goto or a jump statement, functions automatically return to the caller when the function has completed its given task, just as if the code within the function were placed directly into your code (known as inline expansion). Functions are most useful whenever the same statements need to be called over and over from several places in your code, but without the need to duplicate that code (thus reducing maintenance costs). And since functions can call other functions, they can also be used to reduce highly complex functions into much smaller, easier to read functions.

Functions also differ from goto and jump statements in that they can be parametrised. That is, arguments can be passed to the function to alter its behaviour according to a given set of parameters. Moreover, functions can also return a value to the caller. The return value is often used to return an error code to indicate the success or failure of the function, but can also be used to return any one value. If more than one value must be returned, you can either return a complex object (a class, struct or union) or you can use output parameters (parameters may be used to provide input to a function, output from a function, or indeed both).

Parameters and arguments

When discussing functions, you will often encounter the terms parameters and arguments, often prefixed with the terms formal and actual. While many languages do not make any particular distinction between the terms, let's clarify exactly what these terms mean in the general sense.

An argument is an actual parameter or actual argument that is passed to a function from the calling code. In other words, it is the actual variable or constant that you pass into a function.

A parameter is a formal parameter or formal argument that always appears in a function's declaration and/or definition, and is used to accept the arguments passed to it. That is, the arguments are assigned to the parameters. Parameters are often declared but not named within function declarations, but they must be named in function definitions if the function's definition requires access to that parameter. Parameters that are declared but not named in a definition cannot be used by the definition, and are often called dummy parameters.

Function Signatures

The name of a function and the parameters it accepts determine the function's signature. The function signature is used to disambiguate functions that have the same name but different parameters, known as function overloading. The return type of a function does not form any part of its signature, thus overloaded functions cannot differ by return type alone.

Types of Functions

In C++ there are essentially just two major types of function: external functions and member functions. A member function is also known as a method or member method, and is always declared to be a member of a class. Access to the method is determined by the class in which it is declared. External functions do not belong to any class and can be called from any function or class that has access to it.

Methods can also be classified by what they do. Accessor functions are used to retrieve information from the class while mutators manipulate the information within the class. Operators are methods that perform operations upon the information (such as assignment and equality). Operators can also be used to dynamically cast objects to different classes of object or even primitive data types. Special methods known as constructors initialise the class while a destructor cleans up the class when it falls from scope. Unlike other methods and functions, neither constructors nor destructors return any value, not even void. Methods can also be further classified as being non-virtual, virtual and pure-virtual in order to provide any combination of concrete and abstract interfaces to the class.

External functions usually provide auxiliary or utility functionality to a program. Such functions are usually miscellaneous in terms of their functionality and although some could be combined and classified to become member methods, the additional work required to design a class around them will often outweigh the usefulness in having the class. However, if the external functions require access to global data, it is better to combine those functions and the global data into a class, if only to eliminate the need for global data (which is generally a good thing).

C++ also includes many built-in functions made available though the standard library, including template classes and functions. Combined with user-defined classes and functions, these greatly reduce the need to design your own classes and functions entirely from scratch.

Get and set method definition in c plus plus?

Accessors (getters) and mutators (setters) are defined as you would define any member function, usually using the attribute's name prefixed with get_ or set_ as appropriate. Accessors are typically defined as constant member functions that return values (copies of attributes), but you can also return references and pointers to the actual attributes if required, even though these can both undermine encapsulation. However, returning constant references or contant pointers to constant types ensures encapsulation is maintained without creating any unecessary copies of an object (the caller can make a volatile copy when desired). Mutators typically accept a constant value, reference or pointer and act as a data validator, verifying that the incoming data is acceptable before physically setting the member. The return value of a mutator is often void, but when validation is not a concern, it can be useful to return the current value (prior to mutation), thus allowing the caller to easily determine if the object has been mutated or not.

Im making a chess game in c plus plus using names for pieces how do you create a string matrix for the board?

One way to represent the state of a chess board as a string matrix containing names of pieces, is to have an array of pointers. Each pointer would either point to a piece name, or it would be NULL, indicating no piece is there...

char *board[8][8];

int i, j;

for (i=0; i<8; i++) for (j=0; j<8; j++) board[i][j] = NULL; // clear board

board[0][0] = "White Rook";

board[0][1] = "White Bishop";

board[1][0] = "White Pawn"; // etc...

C plus plus programme to count non-vowels in a file of test?

#include<iostream>

#include<fstream>

#include<string>

int main()

{

size_t count=0;

std::string vowels ("aeiouAEIOU");

std::ifstream ifs;

ifs.open ("test.txt", std::ios::in);

if (ifs.bad())

{

ifs.close();

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

return;

}

while (!ifs.eof())

{

char c = ifs.get();

if ((c>='a' && c<='z') (c>='A' && c<='Z'))

if (vowels.find (c) != vowels.npos)

++count;

}

ifs.close();

std::cout << "The file has " << count << " non-vowels.\n" << std::endl;

}

How do you write a program in c plus plus to remove fifth element in the array?

To remove any element from an array, you must overwrite every element from that point on with the element that follows it. That is, every element after the removed element must be copied to the preceding element. So to remove the 5th element, you copy the 6th element to the 5th element, the 7th to the 6th, and so on. Once all elements have been copied, you can reduce the array size by one element. Alternatively, you can leave the array size as is and simply maintain a count of the used elements (unused elements will always be at the end of the array).


Note that in C++, a vector encapsulates an array of any type and provides member methods for manipulating that array, including the removal of individual elements. While manipulating arrays is a worthwhile exercise in determining "how things work", it's always better to make use of efficient, tried-and-tested code, rather than constantly re-inventing wheels to provide such common functionality.

Is type checking on pointer variables stronger in assembly language or in c plus plus?

C++ imposes far greater restrictions on pointer typing than assembly language. There is only a single type of pointer in assembly, which is only "typed" in any sense when dereferenced, and even then only by size. C++ pointer typing takes into account not only the size of the type of the referent, but a number of other factors, such as its relationship to other types in the class hierarchy. The only way to disable these safety checks is to explicitly break the type system using reinterpret_cast.

Why is searching in a sorted list faster than searching in an unsorted list?

With an unsorted list you have to search from the beginning to locate the item you're looking for. This is a linear search which takes linear time O(n) for n items. That is, the best case is constant time O(1) if the item you're looking for is the first item, it is O(n) if it is the last item (or the item doesn''t exist). Thus, on average, searches will take O(n/2) if the item exists, but always takes O(n) if it doesn't.

With a sorted list you start in the middle of the list. If the item you're looking for is less than this item, you can safely discard the upper half of the list but if it is greater you can discard the lower half. In other words you reduce the number of items to be searched by half. You then repeat the process with the remaining half. If the item you're looking for is equal to the middle item, you're done, but if the remaining half has no items the item does not exist. This is a logarithmic search with a best case of O(1), a worst case of O(log n) and an average case of O((log n)/2).

Logarithmic searches are clearly faster, on average, than linear searches. However, logarithmic searches require two separate comparison operations (equal to and less than) while linear searches require just one (equal to). Thus for a list of three or four items, a linear search is arguably quicker. But for larger lists, logarithmic search is quicker. Note that we don't need to test for greater than since it can be assumed that if an item is neither less than or equal to another item, then it must be greater.

C plus plus code for selling cellular phones it should be able to add view search and delete Product ID No Product No country brand and cost?

#include<iostream>

#include<map>

#include<string>

#include<sstream>

#include<conio.h>

struct Cellphone

{

std::string product_id;

std::string product_no;

std::string country;

std::string brand;

double cost;

};

std::ostream& operator<< (std::ostream& os, const Cellphone& phone)

{

os << "Product ID: " << phone.product_id << std::endl;

os << "Product No: " << phone.product_no << std::endl;

os << "Country: " << phone.country << std::endl;

os << "Brand: " << phone.brand << std::endl;

os << "Cost: " << phone.cost << std::endl;

return os;

}

// Global...

std::map<std::string, Cellphone> cellphones;

// forward declarations

size_t choice (std::string);

std::string get_string (std::string prompt);

double get_double (std::string prompt);

void add();

void remove();

void search();

void view();

int main()

{

while (1)

{

std::cout << "MAIN MENU\n=========\n\n";

std::cout << "[A] Add\n";

std::cout << "[V] View\n";

std::cout << "[S] Search\n";

std::cout << "[R] Remove\n";

std::cout << "[Q] Quit\n";

switch (choice ("AVSRQ"))

{

case 0: add(); break;

case 1: view(); break;

case 2: search(); break;

case 3: remove(); break;

default: return 0;

}

}

}

void add ()

{

std::cout << "\nAdd Cellphone\n\n";

Cellphone phone;

phone.product_id = get_string ("Product ID");

phone.product_no = get_string ("Product #");

phone.country = get_string ("Country");

phone.brand = get_string ("Brand");

phone.cost = get_double ("Cost");

cellphones[phone.product_id] = phone;

std::cout << std::endl;

}

void remove ()

{

std::cout << "\nRemove Cellphone\n\n";

std::string id = get_string ("Product ID");

cellphones.erase (id);

}

void search ()

{

std::cout << "\nSearch for Cellphone\n\n";

std::string id = get_string ("Product ID");

std::map<std::string, Cellphone>::const_iterator it = cellphones.find (id);

if (it choices.npos)

continue;

return pos;

}

}

Interface in C plus plus?

Unless by "interface" you mean a user interface...

C++ does not have interfaces per se, at least not in the same sense as, say, Java. In a C++ class, a function declared pure virtual makes the class non-instantiable and forces derived classes that want to be instantiable to provide an implementation. This has exactly the same effect as the interface concept of Java. So in C++, interface is just a synonym for abstract base class.

How do you use the clearscreen command in Microsoft visual c plus plus 6.0?

There is no such "command" in C++, let alone Visual C++. You are probably referring to the Turbo C++ clearscreen function. It is a 3rd party, user-defined function and is therefore not part of the C++ language itself.

You can roll your own clearscreen function, of course. The following is merely an example implementation, but note that this function is not cross-platform compatible because it employs platform-specific code.

You will also need platform-specific code to reposition the cursor after clearing the screen. As it stands, the cursor will be positioned 1000 characters from the top left of the console (immediately after the last insertion position).

#include<iostream>

#include<windows.h> // Non-cross platform, Windows only!

void ClearScreen( void )

{

HANDLE hConsoleOut;

CONSOLE_SCREEN_BUFFER_INFO csbiInfo;

DWORD dummy;

COORD home = { 0, 0 };

hConsoleOut = GetStdHandle( STD_OUTPUT_HANDLE );

GetConsoleScreenBufferInfo( hConsoleOut, &csbiInfo );

FillConsoleOutputCharacter( hConsoleOut, ' ', csbiInfo.dwSize.X * csbiInfo.dwSize.Y, home, &dummy );

}

int main()

{

// print some garbage:

int max=1000;

while(max--)

std::cout<<rand();

ClearScreen();

}

How you can override base class member in derived classexplain with example?

To override a base class method you simply need to declare the base class method as being virtual. As well as creating a v-table, this also gives a visual hint to other developers that you expect the function to be overridden. The v-table ensures that all calls to the base class method are routed to the derived class method, thus ensuring objects behave polymorphically, according to their actual type, and not what we're actually pointing at.

Consider the following example:

#include <iostream>

class base

{

public:

virtual ~base();

virtual void PrintMe() const { std::cout << "I am a base class!" << std::endl; }

};

class derived: public base

{

public:

void PrintMe() const { std::cout << "I am a derived class!" << std::endl; }

};

int main()

{

base b;

derived d;

base* pb = &d;

b.PrintMe();

d.PrintMe();

pb->PrintMe();

return( 0 );

}

Output:

I am a base class!

I am a derived class!

I am a derived class!

Note that although pb points to the base class instance of d, it still knows that it really is a derived class, as can be seen from the third line of output.

Now try removing the virtual keyword from the base class method. The output will change as follows:

Output:

I am a base class!

I am a derived class!

I am a base class!

Now your derived class thinks it is a base class. This is because the v-table no longer has no entry for that method, and therefore the call cannot be routed to the overridden derived class method. The base class method is called because that's what we're actually pointing at and the object no longer behaves polymorphically according to its actual type.

Note also that if any method is declared virtual in a class, the class constructor must also be declared virtual. If you fail to do this, your classes will not be destroyed properly. The virtual keyword ensures that the most-derived class is always destroyed first, before working up the hierarchy of destructors to eventually destroy the least-derived class, the base class itself.

Consider the following example without a virtual destructor:

#include <iostream>

class base

{

public:

base(){ std::cout << "Base class created" << std::endl; }

~base(){ std::cout << "Base class destroyed" << std::endl; }

};

class derived: public base

{

public:

derived(){ std::cout << "Derived class created" << std::endl; }

~derived(){ std::cout << "Derived class destroyed" << std::endl; }

};

int main()

{

derived* d = new derived();

base* b = d;

delete( b );

return( 0 );

}

Output:

Base class created

Derived class created

Base class destroyed

As you can see, the derived class was created but was not destroyed. We've created a memory leak: that memory cannot be recovered until the program ends.

Now add the virtual keyword to the base class destructor:

#include <iostream>

class base

{

public:

base(){ std::cout << "Base class created" << std::endl; }

virtual ~base(){ std::cout << "Base class destroyed" << std::endl; }

};

class derived: public base

{

public:

derived(){ std::cout << "Derived class created" << std::endl; }

~derived(){ std::cout << "Derived class destroyed" << std::endl; }

};

int main()

{

derived* d = new derived();

base* b = d;

delete( b );

return( 0 );

}

Output:

Base class created

Derived class created

Derived class destroyed

Base class destroyed

Now we have the expected behaviour and have resolved the memory leak. Remember, if ANY method of a class is declared virtual, the destructor must also be declared virtual.

Note that although derived classes need not use the virtual keyword in front of overrides (it is implied by the base class), there is no harm in explicitly declaring them as such, if only to give a visual hint that the methods are expected to be overridden by derivatives of the derivative (multi-level inheritance).

Define unary operator explain different unary operators used in c language?

A unary operator is one that requires only one operand. The unary operators are the prefix and postfix increment and decrement, positive and negative, logical and bitwise negation, and address and indirection operators, plus the words alignof, typeof, and sizeof.

The first two operators are increment "++", and decrement "--". Its position before or after the variable determines prefix or postfix. Incrementing increases the stored value by 1, and decrementing decreases the stored value by 1. If it is to the left of the variable, the operation occurs before the variable is used; if it is to the right, it occurs after the variable is used.


The positive operator "+" simply asserts the current value, and exists as acomplementto the negation operator "-". The negation operator returns the number with the opposing sign. If x is 5, then -x is -5, and if x is -5, then -x is 5.


The logical negation "!" and bitwise negation "~" operators perform actions on individual bits. C considers zero to be false, and all other values to be true. Using logical negation, it returns true if the value is zero, or false for any other value. The bitwise negation changes all 1 bits to 0 bits, and 0 bits to 1 bits. For an unsigned byte, ~0 becomes 255, and ~255 becomes 0. For signed variables, ~0 would become -1, and ~-1 would become 0. This is because of the two's complement method of signed numbers.


Address "&" and indirection "*" operators take the address or value of the operand. The address operator allows a variable to be passed by reference; modifying the reference will modify the original value. Using the indirection operator treats a variable as a memory address, which allows the programmer to access a specific spot in memory.


Alignof, sizeof, and typeof are all used to determine the alignment, size, and type of objects dynamically. This is necessary when trying to determine how data is laid out when there may be differences in memory accesses across platforms (e.g. when reading a ZIP file's directory contents).

How many bytes are allocated in the bool data type?

bool (lowercase, built-in type) has an unspecified size, but is typically 1 byte. When in doubt, use sizeof( <type> ) to determine the byte count of any data type.

Program to implement mouse coordinate in vc plus plus?

Start by creating a non-empty WIN32 application.

In your main source, include the standard I/O library:

#include

In the global variables section of your main source, add the following class declaration and object:

struct point

{

int x;

int y;

point():x(0),y(0){}

TCHAR* get() const

{

static TCHAR str[MAX_LOADSTRING];

_stprintf_s(str, MAX_LOADSTRING, "Mouse: %i,%i", x, y);

return(str);

}

};

point mouse_coordinate;

In your WndProc callback function, add the following message handler:

case WM_MOUSEMOVE:

mouse_coordinate.x=LOWORD(lParam);

mouse_coordinate.y=HIWORD(lParam);

RECT r;

GetClientRect(hWnd,&r);

InvalidateRect(hWnd,&r,TRUE);

break;

Finally, modify the WM_PAINT message handler as follows:

case WM_PAINT:

hdc = BeginPaint(hWnd, &ps);

// TODO: Add any drawing code here...

TextOut(hdc, 0, 0, mouse_coordinate.get(), _tcsnlen(mouse_coordinate.get(),MAX_LOADSTRING));

EndPaint(hWnd, &ps);

break;

Now run the application. The mouse coordinates will be printed at the top left of the client area.

Declare a one-dimensional array 'num' of type int and a two-dimensional array 'matrix' of type float digrammatically explain those arrays?

// one dimensional array 'num' of type int...

int num[100];

{Sorry, diagrams are not possible in wiki.answers.com, you have to use words}

This is 100 copies of an integer data type, arranged sequentially in memory. The first one is called num[0], the tenth one is called num[9], and the 100th one is called num[99].

// two dimensional array 'matrix' of type float...

float matrix[10][20];

This is 200 copies of a floating point data type, arranged sequentially in memory. The first one is called matrix[0][0], the tenth one is called matrix[9][0], the eleventh one is called matrix[0][1], and the 200th one is called matrix[9][19].

In both cases, you don't want to "think" about the arrangement of bits and bytes within each int or float. Doing so is non-portable, and can lead to problems down the road. The only safe thing you can consider is the arrangement in memory of the copies of the fundamental type int or float.

What is the purpose of the multiprocessing in computer system structure?

The primary purpose of multiprocessing is to allow more than one process to run, or to appear to run, at the same time. This allows more work to be done more quickly, because one process can be running while another is waiting on something else, so it allows the CPU to be more efficiently utilized. Multiprocessing is an architecture that allows the concept of multiple processes, each lined up to compete for execution by the CPU. The operating system manages the dispatching of each process according to a priority scheme. Processes can be ready, which means the OS can dispatch them to run, or they can be blocked, which means they are unable to be dispatched because they are waiting on some event, such as IO completion, keyboard entry, another process, something. Done correctly, which most modern OS's do very well, it will seem that you can run multiple processes at the same time. If there is only one CPU, then only one process can be running, or dispatched, at any one time. Still, the appearance of concurrent execution will exist. If there is more than one CPU, such as in a dual or quad core processor, then the OS is able to dispatch more than one process at the same time. This is true parallel execution. In modern OS's, the concept of threading exists. Processes and threads are somewhat similar. While different OS's have different terms for processes and threads, it is general convention that a process is an address space supporting a program, with one or more threads running within it. Threads, on the other hand, are what the OS actually manages in term of dispatchability. A thread, then, is an execution path through a process. You can write a program that has only one thread, and the OS will handle it accordingly. If you have several "things" to do within that program, you are responsible for the dispatching of those "things". Well, those "things" can be threads. You can write code that initiates additional threads within your process, each designed to handle one "thing". You then turn dispatch management over to the OS, and you have now written a multi-threaded application. Whether we call them threads or processes or something else, the issue of thread safety is paramount. Thread safety is the ability of a thread to properly access and potentially modify a data structure that is shared between threads (or processes) without creating corruption of data. Various kinds of interlocking mechanisms exist to handle this - it is a big topic, and one that requires great care in its design.

What is inner returns in c plus plus?

Inner returns is not part of standard terminology, so it's difficult to say exactly what it means. It sounds as though it means a return statement other than the one that would typically appear as the final statement in a function. For instance:

int foo(int x)

{

if(!x)

return(-1); // inner return?

return(x*x); // typical return?

}

Differentiating return statements in this way is somewhat meaningless. All we're really saying is that the function has multiple return paths, in this case 2 distinct return paths. A more complex function might have several return paths, some more deeply nested than others, but it makes no real difference, so long as every reachable path has a return statement. In some cases, a function may not have a final return statement at all, simply because the function is guaranteed to never reach that point, because all possible routes through the function lead to an "inner" return path. For example:

int foo(int x)

{

if(!x)

return(-1);

switch(x)

{

case(1): return(x);

case(2): return(x*x);

default: return(x*x*x);

}

}

In the above example, there is no return statement before the final closing brace, because the code is guaranteed never to reach that point. All the return paths are "inner" returns.

We could just as easily write the exact same function as follows:

int foo(int x)

{

switch(x)

{

case(0): return(-1);

case(1): return(x);

case(2): return(x*x);

defaut: return(x*x*x);

}

}

Or this way:

int foo(int x)

{

switch(x)

{

case(0): return(-1);

case(1): return(x);

case(2): return(x*x);

}

return(x*x*x);

}

The logic is the same in each case, it's just a question of which is easier to read and understand. Out of all three, the second is perhaps the simplest to understand because all the logic is contained within the switch statement. But as far as the compiler is concerned, there should be no difference. A good optimiser should compile all three with exactly the same assembly instructions.

Can you access in drive class from base class private data?

Base class should no knowledge about derived classes.

The "private" modifier on a data member means private to the class which defined it. Base class cannot directly reference/access the private data member of the derived class, and the derived classes cannot access the private data member defined in the base class.

Either way the accessing the private data member should be done via properties or getters

Explain Selection control statements and Iteration statements in C plus plus?

Selection control statements in C++

There are basically two types of control statements in c++ which allows the programmer to modify the regular sequential execution of statements.They are selection and iteration statements. The selection statements allow to choose a set of statements for execution depending on a condition. If statement and switch statement are two statements which allow selection in c++. There is also an operator known as conditional operator which enables selection.

If statement

Syntax : if (expression or condition)

{ statement 1;

statement 2;

}

else

{ statement 3;

statement 4;

}

The expression or condition is any expression built using relational operators which either yields true or false condition. If no relational operators are used for comparison, then the expression will be evaluated and zero is taken as false and non zero value is taken as true. If the condition is true, statement1 and statement2 is executed otherwise statement 3 and statement 4 is executed. Else part in the if statement is optional. If there is no else part, then the next statement after the if statement is exceuted, if the condition is false. If there is only one statement to be executed in the if part or in the else part, braces can be omitted.

Following example program implements the ifstatement.

// evenodd.cpp

# include

# include

void main()

{

int num;

cout<<"Please enter a number"<

cin>>num;

if ((num%2) to compare whether remainder is equal to zero or not.

Switch statement

Nested ifs can be confusing if the if statement is deeply nested. One alternative to nested if is the switch statement which can be used to increase clarity in case of checking the different values of the same variable and execute statements accordingly.

Syntax :

Switch (variablename)

{ case value1: statement1;

break;

case value2: statement2;

break;

case value3: statement3;

break;

default: statement4;

}

Iteration statements in C++

Iteration or loops are important statements in c++ which helps to accomplish repeatitive execution of programming statements. There are three loop statements in C++ : while loop, do while loop and for loop

While loop

Syntax: while (condition expression)

{

Statement1;

Statement 2;

}

Do..while loop

The do while loop is same as while loop except that the condition is checked after the execution of statements in the do..while loop. Hence in do..while loop, statements inside the loop are executed atleast once. However, in while loop, since the condition is checked before, the statements inside the loop will not be executed if the loop condition is false.

Do..while Statement

Please note that there is no semicolon after do, but there is a semicolon after the condition expression in while part.

Write a program in c plus plus that will convert an integer pointer into an integer and viceversa?

You cannot physically convert variables of one type to another type, you can only cast them to create a new type (a new variable), providing the new type is covariant with the existing type.

int i = 100; // int variable

int* p = &i; // pointer to int

The indirect value of p is i (100) while the direct value of p is the address of i. And because p is a variable, it has an address of its own. Thus converting the pointer p to an int can be done in one of three ways:

int j = *p; // assign indirect value of p to j (thus j==100).

int k = (int) p; // cast the address stored in p and assign to k (k==address of i)

int l = (int) &p; // cast the address of p and assign to l (l==address of p)

How can you convert binary number into decimal number using g plus plus compiler?

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);

}

Is sql used in c plus plus and cobol language?

Not as part of the formal language, but you can use SQL in various languages, including C++ or Cobol, if you have an appropriate precompiler that allows you to interface with the desired DBMS, be it Oracle, DB2, or whatever. You can also use an interface, such as OCI, if you want. Again, none of these methods are strictly a part of the language.