Programming, website development forum Get latest updates by RSS Follow TechnicalTalk on Twitter Follow TechnicalTalk on Facebook 
HomeSearchRecent PostsLoginRegisterContact Us

Username  
Password    
  Forgot your password?  

Pages: [1]   Go Down
 
  Email this topic  |  Print
0 Members and 1 Guest are viewing this topic.

Frequently asked C++ Questions - C++ FAQs - Interview Questions

 
webmaster forum
Admin  Offline
*
 
Code Guru
Location: India
Gender: Male
Posts: 1387
Topics: 105
NaviBuster NaviBuster
WWW
December 13, 2008, 06:01:37 AM

Here we are trying to collect all the frequently asked questions on C++ programming language. The questions and answers listed in this thread are collected from regular posts by our forum member. You can use them in your interview also. We will try to update this thread regularly, and we are also open for your suggestions.

You may find solution to your programming problem/question in this thread; therefore go through this thread carefully if this is your first visit to the forum in search of some solution.
« Last Edit: May 13, 2011, 05:42:51 AM by Admin »
 
webmaster forum
Admin  Offline
*
 
Code Guru
Location: India
Gender: Male
Posts: 1387
Topics: 105
NaviBuster NaviBuster
WWW
January 17, 2009, 09:54:50 AM

What is C++?

C++ is a programming language. It literally means "increased C", reflecting its nature as an evolution of the C language.


Is it necessary to already know another programming language before learning C++?

Not necessarily. C++ is a simple and clear language in its expressions. It is true that a piece of code written with C++ may be seen by a stranger of programming a bit more cryptic than some other languages due to the intensive use of special characters ({}[]*&!|...), but once one knows the meaning of such characters it can be even more schematic and clear than other languages that rely more on English words.
Also, the simplification of the input/output interface of C++ in comparison to C and the incorporation of the standard template library in the language, makes the communication and manipulation of data in a program written in C++ as simple as in other languages, without losing the power it offers.

How can I learn C++?

There are many ways. Depending on the time you have and your preferences. The language is taught in many types of academic forms throughout the world, and can also be learn by oneself with the help of tutorials and books. The documentation section of this Website contains an online tutorial to help you achieve the objective of learning this language.

What is OOP: Object-oriented programming?

It is a programming model that treats programming from a perspective where each component is considered an object, with its own properties and methods, replacing or complementing structured programming paradigm, where the focus was on procedures and parameters.

What is ANSI-C++?

ANSI-C++ is the name by which the international ANSI/ISO standard for the C++ language is known. But before this standard was published, C++ was already widely used and therefore there is a lot of code out there written in pre-standard C++. Referring to ANSI-C++ explicitly differentiate it from pre-standard C++ code, which is incompatible in some ways.


What is Visual C++? And what does "visual programming" mean?

Visual C++ is the name of a C++ compiler with an integrated environment from Microsoft. It includes special tools that simplify the development of large applications as well as specific libraries that improve productivity. The use of these tools is generally known as visual programming. Other manufacturers also develop these types of tools and libraries, like Borland C++, Visual Age, etc...


Is C++ a practical language?

Yes.

C++ is a practical tool. It's not perfect, but it's useful.

In the world of industrial software, C++ is viewed as a solid, mature, mainstream tool. It has widespread industry support which makes it "good" from an overall business perspective.


Is C++ a perfect language?

Nope.

C++ wasn't designed to demonstrate what a perfect OO language looks like. It was designed to be a practical tool for solving real world problems. It has a few warts, but the only place where it's appropriate to keep fiddling with something until it's perfect is in a pure academic setting. That wasn't C++'s goal.


What's the big deal with OO?

Object-oriented techniques are the best way we know of to develop large, complex software applications and systems.

OO hype: the software industry is "failing" to meet demands for large, complex software systems. But this "failure" is actually due to our successes: our successes have propelled users to ask for more. Unfortunately we created a market hunger that the "structured" analysis, design and programming techniques couldn't satisfy. This required us to create a better paradigm.

C++ is an OO programming language. C++ can also be used as a traditional programming language (as "as a better C"). However if you use it "as a better C," don't expect to get the benefits of object-oriented programming.

What is a class?

The fundamental building block of OO software.

A class defines a data type, much like a struct would be in C. In a computer science sense, a type consists of both a set of states and a set of operations which transition between those states. Thus int is a type because it has both a set of states and it has operations like i + j or i++, etc. In exactly the same way, a class provides a set of (usually public:) operations, and a set of (usually non-public:) data bits representing the abstract values that instances of the type can have.

You can imagine that int is a class that has member functions called operator++, etc. (int isn't really a class, but the basic analogy is this: a class is a type, much like int is a type.)

Note: a C programmer can think of a class as a C struct whose members default to private. But if that's all you think of a class, then you probably need to experience a personal paradigm shift.

What is an object?

A region of storage with associated semantics.

After the declaration int i; we say that "i is an object of type int." In OO/C++, "object" usually means "an instance of a class." Thus a class defines the behavior of possibly many objects (instances).

When is an interface "good"?

When it provides a simplified view of a chunk of software, and it is expressed in the vocabulary of a user (where a "chunk" is normally a class or a tight group of classes, and a "user" is another developer rather than the ultimate customer).

What is encapsulation?

Preventing unauthorized access to some piece of information or functionality.

The key money-saving insight is to separate the volatile part of some chunk of software from the stable part. Encapsulation puts a firewall around the chunk, which prevents other chunks from accessing the volatile parts; other chunks can only access the stable parts. This prevents the other chunks from breaking if (when!) the volatile parts are changed. In context of OO software, a "chunk" is normally a class or a tight group of classes.

The "volatile parts" are the implementation details. If the chunk is a single class, the volatile part is normally encapsulated using the private: and/or protected: keywords. If the chunk is a tight group of classes, encapsulation can be used to deny access to entire classes in that group. Inheritance can also be used as a form of encapsulation.

The "stable parts" are the interfaces. A good interface provides a simplified view in the vocabulary of a user, and is designed from the outside-in (here a "user" means another developer, not the end-user who buys the completed application). If the chunk is a single class, the interface is simply the class's public: member functions and friend functions. If the chunk is a tight group of classes, the interface can include several of the classes in the chunk.

Designing a clean interface and separating that interface from its implementation merely allows users to use the interface. But encapsulating (putting "in a capsule") the implementation forces users to use the interface.


Is Encapsulation a Security device?

No.

Encapsulation != security.

Encapsulation prevents mistakes, not espionage.

What's the difference between the keywords struct and class?

The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

struct and class are otherwise functionally equivalent.

OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.

What is a reference?

An alias (an alternate name) for an object.

References are frequently used for pass-by-reference:

Code:
    void swap(int& i, int& j)
    {
      int tmp = i;
      i = j;
      j = tmp;
    }
   
    int main()
    {
      int x, y;
      // ...
      swap(x,y);
    }

Here i and j are aliases for main's x and y respectively. In other words, i is x — not a pointer to x, nor a copy of x, but x itself. Anything you do to i gets done to x, and vice versa.

OK. That's how you should think of references as a programmer. Now, at the risk of confusing you by giving you a different perspective, here's how references are implemented. Underneath it all, a reference i to object x is typically the machine address of the object x. But when the programmer says i++, the compiler generates code that increments x. In particular, the address bits that the compiler uses to find x are not changed. A C programmer will think of this as if you used the C style pass-by-pointer, with the syntactic variant of (1) moving the & from the caller into the callee, and (2) eliminating the *s. In other words, a C programmer will think of i as a macro for (*p), where p is a pointer to x (e.g., the compiler automatically dereferences the underlying pointer; i++ is changed to (*p)++; i = 7 is automatically changed to *p = 7).

Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object.

What happens if you return a reference?

The function call can appear on the left hand side of an assignment operator.

This ability may seem strange at first. For example, no one thinks the expression f() = 7 makes sense. Yet, if a is an object of class Array, most people think that a = 7 makes sense even though a is really just a function call in disguise (it calls Array::operator[](int), which is the subscript operator for class Array).

Code:
    class Array {
    public:
      int size() const;
      float& operator[] (int index);
      // ...
    };
   
    int main()
    {
      Array a;
      for (int i = 0; i < a.size(); ++i)
        a[i] = 7;    // This line invokes Array::operator[](int)
    }


When should I use references, and when should I use pointers?

Use references when you can, and pointers when you have to.

References are usually preferred over pointers whenever you don't need "resetting". This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

The exception to the above is where a function's parameter or return value needs a "sentinel" reference. This is usually best done by returning/taking a pointer, and giving the NULL pointer this special significance (references should always alias objects, not a deference NULL pointer).

Note: Old line C programmers sometimes don't like references since they provide reference semantics that isn't explicit in the caller's code. After some C++ experience, however, one quickly realizes this is a form of information hiding, which is an asset rather than a liability. E.g., programmers should write code in the language of the problem rather than the language of the machine.

Is there any difference between List x; and List x();?

A big difference!

Suppose that List is the name of some class. Then function f() declares a local List object called x:

    void f()
    {
      List x;     // Local object named x (of class List)
      // ...
    }

But function g() declares a function called x() that returns a List:

    void g()
    {
      List x();   // Function named x (that returns a List)
      // ...
    }


How can I make a constructor call another constructor as a primitive?

No way.

Dragons be here: if you call another constructor, the compiler initializes a temporary local object; it does not initialize this object. You can combine both constructors by using a default parameter, or you can share their common code in a private init() member function.

What is a destructors?

A destructor gives an object its last rites.

Destructors are used to release any resources allocated by the object. E.g., class Lock might lock a semaphore, and the destructor will release that semaphore. The most common example is when the constructor uses new, and the destructor uses delete.

Destructors are a "prepare to die" member function. They are often abbreviated "dtor".


What's the order that local objects are destructed?

In reverse order of construction: First constructed, last destructed.

In the following example, b's destructor will be executed first, then a's destructor:

    void userCode()
    {
      Fred a;
      Fred b;
      // ...
    }

What's the order that objects in an array are destructed?

In reverse order of construction: First constructed, last destructed.

In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]:

    void userCode()
    {
      Fred a[10];
      // ...
    }


Can I overload the destructor for my class?

No.

You can have only one destructor for a class Fred. It's always called Fred::~Fred(). It never takes any parameters, and it never returns anything.

You can't pass parameters to the destructor anyway, since you never explicitly call a destructor (well, almost never).


Should I explicitly call a destructor on a local variable?

No!

The destructor will get called again at the close } of the block in which the local was created. This is a guarantee of the language; it happens automatically; there's no way to stop it from happening. But you can get really bad results from calling a destructor on the same object a second time! Bang! You're dead!


What is "self assignment"?

Self assignment is when someone assigns an object with itself. For example,

    #include "Fred.hpp"    // Declares class Fred
   
    void userCode(Fred& x)
    {
      x = x;   // Self-assignment
    }

Obviously no one ever explicitly does a self assignment like the above, but since more than one pointer or reference can point to the same object (aliasing), it is possible to have self assignment without knowning it:

    #include "Fred.hpp"    // Declares class Fred
   
    void userCode(Fred& x, Fred& y)
    {
      x = y;   // Could be self-assignment if &x == &y
    }
   
    int main()
    {
      Fred z;
      userCode(z, z);
    }


What is an operator overloading?

It allows you to provide an intuitive interface to users of your class.

Operator overloading allows C/C++ operators to have user-defined meanings on user-defined types (classes). Overloaded operators are syntactic sugar for function calls:

    class Fred {
    public:
      // ...
    };
   
    #if 0
   
      // Without operator overloading:
      Fred add(Fred, Fred);
      Fred mul(Fred, Fred);
   
      Fred f(Fred a, Fred b, Fred c)
      {
        return add(add(mul(a,b), mul(b,c)), mul(c,a));    // Yuk...
      }
   
    #else
   
      // With operator overloading:
      Fred operator+ (Fred, Fred);
      Fred operator* (Fred, Fred);
   
      Fred f(Fred a, Fred b, Fred c)
      {
        return a*b + b*c + c*a;
      }
   
    #endif


What are the benefits of operator overloading?

By overloading standard operators on a class, you can exploit the intuition of the users of that class. This lets users program in the language of the problem domain rather than in the language of the machine.

The ultimate goal is to reduce both the learning curve and the defect rate.


What is a friend?

Something to allow your class to grant access to another class or function.

Friends can be either functions or other classes. A class grants access privileges to its friends. Normally a developer has political and technical control over both the friend and member functions of a class (else you may need to get permission from the owner of the other pieces when you want to update your own class).


Do friends violate encapsulation?

If they're used properly, they actually enhance encapsulation.

You often need to split a class in half when the two halves will have different numbers of instances or different lifetimes. In these cases, the two halves usually need direct access to each other (the two halves used to be in the same class, so you haven't increased the amount of code that needs direct access to a data structure; you've simply reshuffled the code into two classes instead of one). The safest way to implement this is to make the two halves friends of each other.

If you use friends like just described, you'll keep private things private. People who don't understand this often make naive efforts to avoid using friendship in situations like the above, and often they actually destroy encapsulation. They either use public data (grotesque!), or they make the data accessible between the halves via public get() and set() member functions. Having a public get() and set() member function for a private datum is OK only when the private datum "makes sense" from outside the class (from a user's perspective). In many cases, these get()/set() member functions are almost as bad as public data: they hide (only) the name of the private datum, but they don't hide the existence of the private datum.

Similarly, if you use friend functions as a syntactic variant of a class's public: access functions, they don't violate encapsulation any more than a member function violates encapsulation. In other words, a class's friends don't violate the encapsulation barrier: along with the class's member functions, they are the encapsulation barrier.


What are some advantages/disadvantages of using friend functions?

They provide a degree of freedom in the interface design options.

Member functions and friend functions are equally privileged (100% vested). The major difference is that a friend function is called like f(x), while a member function is called like x.f(). Thus the ability to choose between member functions (x.f()) and friend functions (f(x)) allows a designer to select the syntax that is deemed most readable, which lowers maintenance costs.

The major disadvantage of friend functions is that they require an extra line of code when you want dynamic binding. To get the effect of a virtual friend, the friend function should call a hidden (usually protected:) virtual member function. This is called the Virtual Friend Function Idiom. For example:

    class Base {
    public:
      friend void f(Base& b);
      // ...
    protected:
      virtual void do_f();
      // ...
    };
   
    inline void f(Base& b)
    {
      b.do_f();
    }
   
    class Derived : public Base {
    public:
      // ...
    protected:
      virtual void do_f();  // "Override" the behavior of f(Base& b)
      // ...
    };
   
    void userCode(Base& b)
    {
      f(b);
    }

The statement f(b) in userCode(Base&) will invoke b.do_f(), which is virtual. This means that Derived::do_f() will get control if b is actually a object of class Derived. Note that Derived overrides the behavior of the protected: virtual member function do_f(); it does not have its own variation of the friend function, f(Base&).


Should my class declare a member function or a friend function?

Use a member when you can, and a friend when you have to.

Sometimes friends are syntactically better (e.g., in class Fred, friend functions allow the Fred parameter to be second, while members require it to be first). Another good use of friend functions are the binary infix arithmetic operators. E.g., aComplex + aComplex should be defined as a friend rather than a member if you want to allow aFloat + aComplex as well (member functions don't allow promotion of the left hand argument, since that would change the class of the object that is the recipient of the member function invocation).

In other cases, choose a member function over a friend function.


Does delete p delete the pointer p, or the pointed-to-data *p?

The pointed-to-data.

The keyword should really be delete_the_thing_pointed_to_by. The same abuse of English occurs when freeing the memory pointed to by a pointer in C: free(p) really means free_the_stuff_pointed_to_by(p).


Can I free() pointers allocated with new? Can I delete pointers allocated with malloc()?

No!

It is perfectly legal, moral, and wholesome to use malloc() and delete in the same program, or to use new and free() in the same program. But it is illegal, immoral, and despicable to call free() with a pointer allocated via new, or to call delete on a pointer allocated via malloc().

Beware! I occasionally get e-mail from people telling me that it works OK for them on machine X and compiler Y. That does not make it right! Sometimes people say, "But I'm just working with an array of char." Nonetheless do not mix malloc() and delete on the same pointer, or new and free() on the same pointer! If you allocated via p = new char[n], you must use delete[] p; you must not use free(p). Or if you allocated via p = malloc(n), you must use free(p); you must not use delete[] p or delete p! Mixing these up could cause a catastrophic failure at runtime if the code was ported to a new machine, a new compiler, or even a new version of the same compiler.

You have been warned.

Can I use realloc() on pointers allocated via new?

No!

When realloc() has to copy the allocation, it uses a bitwise copy operation, which will tear many C++ objects to shreds. C++ objects should be allowed to copy themselves. They use their own copy constructor or assignment operator.

Besides all that, the heap that new uses may not be the same as the heap that malloc() and realloc() use!

Do I need to check for NULL before delete p?

No!

The C++ language guarantees that delete p will do nothing if p is equal to NULL. Since you might get the test backwards, and since most testing methodologies force you to explicitly test every branch point, you should not put in the redundant if test.

Wrong:

    if (p != NULL)
      delete p;

Right:

    delete p;





« Last Edit: January 17, 2009, 11:13:26 AM by Admin »
 
webmaster forum
Admin  Offline
*
 
Code Guru
Location: India
Gender: Male
Posts: 1387
Topics: 105
NaviBuster NaviBuster
WWW
January 17, 2009, 10:49:13 AM

Is inheritance important to C++?

Yep.

Inheritance is what separates abstract data type (ADT) programming from OO programming.


When would I use inheritance?

As a specification device.

Human beings abstract things on two dimensions: part-of and kind-of. A Ford Taurus is-a-kind-of-a Car, and a Ford Taurus has-a Engine, Tires, etc. The part-of hierarchy has been a part of software since the ADT style became relevant; inheritance adds "the other" major dimension of decomposition.

How do you express inheritance in C++?

By the : public syntax:

    class Car : public Vehicle {
    public:
      // ...
    };


Why can't my derived class access private: things from my base class?

To protect you from future changes to the base class.

Derived classes do not get access to private members of a base class. This effectively "seals off" the derived class from any changes made to the private members of the base class.

What is a "virtual member function"?

From an OO perspective, it is the single most important feature of C++:

A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

The derived class can either fully replace ("override") the base class member function, or the derived class can partially replace ("augment") the base class member function. The latter is accomplished by having the derived class member function call the base class member function, if desired.

How can C++ achieve dynamic binding yet also static typing?

When you have a pointer to an object, the object may actually be of a class that is derived from the class of the pointer (e.g., a Vehicle* that is actually pointing to a Car object). Thus there are two types: the (static) type of the pointer (Vehicle, in this case), and the (dynamic) type of the pointed-to object (Car, in this case).

Static typing means that the legality of a member function invocation is checked at the earliest possible moment: by the compiler at compile time. The compiler uses the static type of the pointer to determine whether the member function invocation is legal. If the type of the pointer can handle the member function, certainly the pointed-to object can handle it as well. E.g., if Vehicle has a certain member function, certainly Car also has that member function since Car is a kind-of Vehicle.

Dynamic binding means that the address of the code in a member function invocation is determined at the last possible moment: based on the dynamic type of the object at run time. It is called "dynamic binding" because the binding to the code that actually gets called is accomplished dynamically (at run time). Dynamic binding is a result of virtual functions.


What's the difference between how virtual and non-virtual member functions are called?

Non-virtual member functions are resolved statically. That is, the member function is selected statically (at compile-time) based on the type of the pointer (or reference) to the object.

In contrast, virtual member functions are resolved dynamically (at run-time). That is, the member function is selected dynamically (at run-time) based on the type of the object, not the type of the pointer/reference to that object. This is called "dynamic binding." Most compilers use some variant of the following technique: if the object has one or more virtual functions, the compiler puts a hidden pointer in the object called a "virtual-pointer" or "v-pointer." This v-pointer points to a global table called the "virtual-table" or "v-table."

The compiler creates a v-table for each class that has at least one virtual function. For example, if class Circle has virtual functions for draw() and move() and resize(), there would be exactly one v-table associated with class Circle, even if there were a gazillion Circle objects, and the v-pointer of each of those Circle objects would point to the Circle v-table. The v-table itself has pointers to each of the virtual functions in the class. For example, the Circle v-table would have three pointers: a pointer to Circle::draw(), a pointer to Circle::move(), and a pointer to Circle::resize().

During a dispatch of a virtual function, the run-time system follows the object's v-pointer to the class's v-table, then follows the appropriate slot in the v-table to the method code.

The space-cost overhead of the above technique is nominal: an extra pointer per object (but only for objects that will need to do dynamic binding), plus an extra pointer per method (but only for virtual methods). The time-cost overhead is also fairly nominal: compared to a normal function call, a virtual function call requires two extra fetches (one to get the value of the v-pointer, a second to get the address of the method). None of this runtime activity happens with non-virtual functions, since the compiler resolves non-virtual functions exclusively at compile-time based on the type of the pointer.

What is mentoring?

It's the most important tool in learning OO.

Object-oriented thinking is caught, not just taught. Get cozy with someone who really knows what they're talking about, and try to get inside their head and watch them solve problems. Listen. Learn by emulating.

If you're working for a company, get them to bring someone in who can act as a mentor and guide. We've seen gobs and gobs of money wasted by companies who "saved money" by simply buying their employees a book ("Here's a book; read it over the weekend; on Monday you'll be an OO developer").


Should I learn C before I learn OO/C++?

Don't bother.

If your ultimate goal is to learn OO/C++ and you don't already know C, reading books or taking courses in C will not only waste your time, but it will teach you a bunch of things that you'll explicitly have to un-learn when you finally get back on track and learn OO/C++ (e.g., malloc(), printf(), unnecessary use of switch statements, error-code exception handling, unnecessary use of #define macros, etc.).

If you want to learn OO/C++, learn OO/C++. Taking time out to learn C will waste your time and confuse you.


 
webmaster forum
Admin  Offline
*
 
Code Guru
Location: India
Gender: Male
Posts: 1387
Topics: 105
NaviBuster NaviBuster
WWW
January 17, 2009, 11:40:01 AM

Where can I get a C or C++ compiler?

Depends on your operating system. See the following links:
http://www.compilers.net/Dir/Free/Compilers/CCpp.htm
http://www.bloodshed.net/compilers/index.html
http://www.openwatcom.org/ (Formerly Watcom/Sybase compiler)
http://www.digitalmars.com/ (Formerly Symantec/Zortech compiler)
http://community.borland.com/museum/ (Ancient Borland compilers)
http://msdn.microsoft.com/visualc/vctoolkit2003/ (Free Visual C++ 2003 Toolkit)
http://www.borland.com/products/dow...d_cbuilder.html (Borland C++ Builder Trial Version download)

In general, people on this forum generally use the following:
On Unix-like OS (Linux, FreeBSD, OpenBSD, NetBSD, Darwin etc.):
gcc
tendra (this is a relatively unknown compiler though ).

On Windows:
Bloodshed Dev C++ (which uses gcc as the backend)
Visual C++
Borland C++ and Borland C++ Builder


How do I compile my program?

On unix-like systems:
gcc -o exename myfile.c
This will compile myfile.c to produce an executable file called exename. You can then run exename by typing ./exename

On Windows systems, different compilers have different keys to compile a program.
Bloodshed/Dev C++: Ctrl-F9 compiles, Ctrl-F10 executes.
Visual C++: F7 compiles, F5 executes.
Borland C++ Builder: Ctrl-F9 compiles, F9 executes.
Turbo-C: F9 compiles, Ctrl-F9 executes.

Why does my scanf/fscanf/sscanf stop working?

Most C input is provided in a stream. That is, it is a series of characters made available one at a time. The scanf() function family are format-sensitive functions; they not only collect the characters for you, but attempt to convert them to a type (such as an integer) that you specify. They have great difficulty converting ZyGH4 to a meaningful number so they fail. The conversion attempt is governed by format specifiers that YOU provide. Since these may not match the input actually encountered, the family returns a value indicating the number of items successfully scanned AND assigned. If this value is zero, you have nothing. If this value is EOF, there was an end-of-file or other error. If you don't examine the return, how will you know? If an error occurs it will not be automatically cleared. Operations on the stream will continue to return an error until clearerr(), fseek(), fsetpos(), or rewind() is called. This means that a loop that is designed to pause for input will loop indefinitely.

The characters that f/s/scanf attempt to convert as one value are all the characters up to the first whitespace character (space, tab, newline) or up to the specified field width, or up to the first character that cannot be converted. (Note: The [ and c format directives are not whitespace delimited, but we won't consider them for the explanation here). If a character conflicts with the format specification, the function terminates and the character is left in the stream as if it had not been read. You probably will not expect it to be there to serve as input for your next call, so your input will not behave as you expect.

Example of proper usage:
int status;
status = scanf ("%s%d\n", name, &number);

Check the value of 'status' after the scanf() call. If it is not what you expect (two, in this case), you didn't get all your fields. If it is EOF, your stream is broken and will remain so until you clear the error.

Why does getline() not work correctly with Visual C++ (VC++)? Why do I have to type Enter twice for getline to process my input line?

f you're reading this, you've probably noticed that getline() is not functioning the way your book says it should -- you need to hit <enter> twice for the program to read your input. For example:

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    cout<<"Enter a name:\n";
    getline(cin, name);
    cout<<name<<endl;

    return 0;
}

This is because there's a known bug in Visual C++'s implementation of getline() (in the VC++ 6.0 Standard/Professional/Enterprise editions only, .NET has the fix).

How do I convert a char array to integer/double/long type?

Use the atoi(), atof() or atol() functions. Also see question 1.3 below.

Code:
#include <stdlib.h>
int main(void)
{
     char *buf1 = "42";
     char buf2[] = "69.00";
     int i;
     double d;
     long l;
     i = atoi(buf1);
     l = atol(buf1);
     d = atof(buf2);
     return 0;
}


How do I convert an integer/float/double/long type variable to a char array?

Use sprintf(). Many books/websites tell you to use itoa(), itol(), itof() etc., but these functions are compiler specific and are therefore non-portable. sprintf() is definitely the way to go.

Code:
#include <stdio.h>
int main(void)
{
    int i = 42;
    float f = 69.0;
    double d = 105.24;
    long l = 23;
    char buf[50];
 
    sprintf(buf, "%d", i);
    sprintf(buf, "%f", f);
    sprintf(buf, "%f", d);
    sprintf(buf, "%ld", l);
    sprintf(buf, "%d %f %ld", i, f, l);
    return 0;


C++ users may also use the stringstream or ostringstream class (the deprecated form was strstream class)

Code:
#include <sstream>
#include <string>
using namespace std;

int main(void) {
    stringstream ss;
    int i = 42;
    double d = 105.24;

    ss << i << " " << d;

    // Convert to string or char array
    string s = ss.str();
    char buf[50];
    sprintf(buf, ss.str().c_str());
}


How do I convert a hex/octal/any-other-base value to a number?

Use strtol() or sscanf().

Code:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
  long l; int i;
  unsigned int ui;
  char *hexstr = "12FC3";
  char *octstr = "1245";
  char *binarystr = "1101";

  l = strtol(hexstr, NULL, 16);
  l = strtol(octstr, NULL, 8);
  l = strtol(binarystr, NULL, 2);
  sscanf("12", "%d", &i);
  sscanf("14", "%ld", &l);
  sscanf(hexstr, "%x", &ui);
  sscanf(hexstr, "%o", &ui);

  return 0;
}

C++ users may want to use stringstream instead (strstream is deprecated).

Code:
#include <sstream>
#include <string>
using namespace std;

int main(void)
{
  long l; int i;
  char *hexstr = "12FC3";
  char *octstr = "1245";
  stringstream ss;

  ss << hex << hexstr;
  ss >> l;
  ss.clear();
  ss << oct << octstr;
  ss >> i;

  return 0;
}

How do I convert an integer to hexadecimal (hex) /octal (oct)?

Use sprintf().

Code:
#include <stdio.h>
int main(void)
{
    int i = 42;
    char buf[50];
    sprintf(buf, "%x", i); /* convert to hex */
    sprintf(buf, "%o", i); /* convert to octal */
    return 0;
}

C++ users may want to use stringstream instead (strstream is deprecated).

Code:
#include <sstream>
#include <string>
using namespace std;

int main(void)
{
  int i = 42;
  char buf[50];
  stringstream ss;
  ss << hex << i;
  ss >> buf;

  ss.clear();
  ss << oct << i;
  ss >> buf;
  return 0;
}


What's the equivalent of perl/pascal/vb/php's chr() and ord() functions in C/C++?

There aren't any functions like this in C or C++ and they aren't needed anyway. You can get a char's ASCII value by simply assigning it to an integer variable.


Code:
char ch;
int i;

ch = 'A';
i = ch; /* Assigns the ASCII value of 'A' (i.e.) 65 to i */
printf("%d\n", i); /* Prints 65 */

To do the reverse (i.e.) what the ord() function does, simply assign an integer to a char variable. You'll need to force a cast to avoid compiler warnings for some compilers though

Code:
int i;
char ch;

i = 65;
ch = (char) i;
/* some compilers don't warn you if you do:
ch = i;
and some will, hence the explicit cast to char type. The cast
assures the compilers that warn you, that you know what you're doing. */
printf("%c\n", ch); /* prints 'A' */


Since characters and integers are treated somewhat alike in C/C++, you can perform arithmetic operations and comparision operations with char variables, just as you do with integer variables. For instance:


Code:
char ConvertToUpperCase(char ch) {
   if (ch >= 'a' && ch <= 'z')
      ch = ch - 'a' + 'A';
   return ch;
}

The above code takes a variable as input and checks if it is a lowercase letter by comparing its ASCII value to see if it is between the ASCII for 'a' and 'z'. If so, it subtracts the ASCII value of 'a' and adds the ASCII value of 'A', thereby converting it to an uppercase ASCII value.


How do I print an integer/char/char array/float/double/long/long double/long long?


Use appropriate formatting strings (%d, %ld, %f, %Lf, %lld) with your printf statements.


Code:
#include <stdio.h>

int main(void)
{
  int i = 23; long l = 42;
  float f = 105.23; double d = 69.05;
  long double ld = 55.23; long long ll = 92;
  char c='a'; char s[] = "This is a string";

  printf("int = %d\nlong = %ld\n", i, l);
  printf("float = %f\ndouble = %fd\n", f, d);
  printf("long double = %Lf\nlong long = %lld\n", ld, ll);
  printf("char = "%c\nString=%s\n", c, s);

  return 0;
}

C++ users can use cout and not worry about the format string types


How do I limit the precision/length of floating point, double numbers or char strings?

Use the format strings to specify precision.


Code:
#include <stdio.h>

int main(void)
{
  float f = 105.2345;
  char buf[] = "This is a string";

  /* Limit to 2 decimals */
  printf("float = %.2f\n", f);
  /* Print 10 chars wide, limit to 2 decimals */
  printf("float = %10.2f\n", f);
  /* Print 10 chars wide, limit to 2 decimals and left-justify */
  printf("float = %-10.2f\n", f);
  /* Limit to 10 characters */
  printf("%.10s\n", buf);

  return 0;
}


C++ users may use the iomanip functions setprecision() and setw() to do this.


Code:
#include <iostream>
#include <iomanip>
using namespace std;

int main(void)
{
  float f = 105.2345;
  char buf[] = "This is a string";

  cout.setf(ios::fixed);
  /* Limit to 2 decimals */
  cout << setprecision(2) << f << endl;
  /* Print 10 chars wide, limit to 2 decimals */
  cout << setw(10) << setprecision(2) << f << endl;
  /* Right justify to 30 chars */
  cout << setw(30) << buf << endl;

  return 0;
}


How do I control how many chars are read in a string when using scanf()?

You can use the a format specifier in the scanf() function.

Code:
char buf[25];
scanf("%20s", buf);

The above code limits the length of the characters that will be read by scanf() to 20 characters maximum (note that the buffer can hold 25 characters though!)

C++ Users can use either setw() or cin.get()

Code:
cin >> setw(20) >> buf;
cin.get(buf, 20);


Either statement does the same thing. Note that the above code will read 19 characters max and put \0 for the 20th character.


 
webmaster forum
Admin  Offline
*
 
Code Guru
Location: India
Gender: Male
Posts: 1387
Topics: 105
NaviBuster NaviBuster
WWW
January 17, 2009, 11:45:45 AM

HOW TO OPEN AND USE A FILE


Methods for opening files for reading and writing might be classified as C++, C stream, and C low-level methods. There are numerous variations, particularly with C++ streams; this post can in no way be considered exhaustive. CHECK YOUR DOCUMENTATION.

A NOTE ABOUT MODE

Unix/Linux have only one mode for file operations: binary. Windows has a text mode which is, unfortunately, the default. In text mode, content beyond what you supply is written to the file; it is stripped when you read the file. This makes the use of
random access (seek, tell, etc.), problematic. Even worse, a 'soft' EOF, a special character, is written. This indicator is NOT MOVED if you do an append, so appended data is not reachable unless you reset the EOF indication. Consequently, I recommend always using binary mode. With 'fopen,' you can specify a read or write or other mode as "rb", "wb", etc. Unix/Linux will accept and ignore the 'b', so you can use it portably. You can also set the default mode in Windows with the global variable, _fmode.

C++ USING FSTREAM

VC++ 6.0, Windows XP
Include iostream, fstream, and string for the following examples.

FSTREAM
OPENING FOR WRITE


Code:
  // Example variables
   string sFileName = "test.txt";
   string sContents = "File data\n";
   string sToken;
   char   lineBuffer [256];
   int    nCount = 0;

   // Construct an fstream object and attempt to open
   // for output
   fstream ooFile;
   ooFile.open (sFileName.c_str (), ios::binary | ios::out);

   // Test for success
   if (!ooFile.is_open ()) return badHappenstance ("Couldn't open file for writing");

   // Write example
   ooFile << sContents;

   // Test the write for success
   if (!ooFile.good ()) return badHappenstance ("Write failed");

   // Close the file.  Note that the file will be closed automatically when
   // the object is destroyed (goes out of scope).
   ooFile.close ();


OPENING FOR READ

Code:
// Open it for input
   ooFile.open (sFileName.c_str (), ios::binary | ios::in);
   if (!ooFile.is_open ()) return badHappenstance ("Couldn't open file for reading");

   // Read tokens until end of file or error
   while (ooFile.good ())
   {
      ooFile >> sToken;
      cout << "Token " << ++nCount << ": ";
      if (sToken.size ()) cout << sToken; else cout << "(null token)";
      cout << endl;
   }
   // Check some status for grins
   if (ooFile.eof ()) cout << "Reached EOF" << endl;
   else if (ooFile.fail ()) return badHappenstance ("Read failed for some reason");

   // Alternatively, read entire line
   ooFile.getline (lineBuffer, sizeof (lineBuffer));

   // Always the status
   if (!(ooFile.good () || ooFile.eof ()))
      return badHappenstance ("Failure reading line");

   cout << "This is the line: " << lineBuffer << endl;

A SEEK EXAMPLE

Code:
// Position to beginning after clearing EOF or fail bits
   ooFile.clear ();
   ooFile.seekg (0, ios::beg);
   if (!ooFile.good ()) return badHappenstance ("Seek failed");

   ooFile.close ();


Example output:

Code:
Token 1: File
Token 2: data
Token 3: (null token)
Reached EOF
This is the line: File data

C USING FOPEN

VC++ 6.0, Windows XP
Include stdio.h for this method.

OPENING FOR WRITE


Code:
// Example variables
   FILE *ooFile;
   char  sFileName [] = "test.txt";
   char  sContents [] = "File data\n";
   char  sToken [32];
   char  lineBuffer [256];
   int   nCount = 0;
   int   status;

   // Attempt to open file for output
   ooFile = fopen (sFileName, "wb");

   // Test for success
   if (!ooFile) return badHappenstance ("Couldn't open file for writing");

   // Write the contents
   status = fputs (sContents, ooFile);

   // Test for success
   if (status == EOF) return badHappenstance ("Write failed");

   // Close the file
   fclose (ooFile);


OPENING FOR INPUT

Code:
ooFile = fopen (sFileName, "rb");
   if (!ooFile) return badHappenstance ("Couldn't open file for reading");

   // Read tokens until end of file or error -- one method: fscanf
   // fscanf consumes whitespace, unlike some C++ methods
   // so there won't be a null token at the end.
   while (1)
   {
      if (fscanf (ooFile, "%s", sToken) != 1)
      {
         if (feof (ooFile))
         {
            printf ("Reached EOF\n");
            break;
         }
         else return badHappenstance ("Failed to read token");
      }
      printf ("Token %d: %s\n", ++nCount, sToken);
   }
// REPOSITIONING EXAMPLE

   rewind (ooFile);

   // Read a line all in one swell foop
   // We'll either fill the buffer or have a newline
   // at the end of the buffer, or both.  If you don't
   // want the newline:
   //
   //    index = strlen (lineBuffer) - 1;
   //    if (lineBuffer [index] == '\n')
   //        lineBuffer [index] = '\0';"
   //
   if (fgets (lineBuffer, sizeof (lineBuffer), ooFile) == NULL)
      // Always the status; EOF is okay, error is not
      if (ferror (ooFile)) return badHappenstance ("Failed to read line");

   printf ("This is the line: %s", lineBuffer);
   fclose (ooFile);


Example output:


Code:
Token 1: File
Token 2: data
Reached EOF
This is the line: File data


C USING LOW LEVEL _open

As far as I'm concerned, low level file operations are only good for reading large amounts of binary data, and are not necessary for that. One is far better off using the higher level functions.

VC++ 6.0, Windows XP
Include stdio.h, io.h, fcntl.h, sys\stat.h, ctype.h, and string.h for the following example.

OPENING FOR READ/WRITE


Code:
typedef int fileHandle;
extern int errno;

   // Example variables
   fileHandle ooFile;
   char  sFileName [] = "test.txt";
   char  sContents [] = "File data\n";
   char  sToken [32];
   char  sTrash [32];
   char  lineBuffer [256];
   int   nChars, nTokens;
   int   status;

   // Attempt to open file for input/output
   ooFile = _open ("test.txt", _O_CREAT | _O_RDWR | _O_TRUNC | _O_BINARY, _S_IWRITE);

   // Test for success
   if (ooFile == EOF) return badHappenstance (strerror (errno));


WRITING


Code:
// Write the contents
   status = _write (ooFile, sContents, strlen (sContents));

   // Test for success
   if (status == EOF) return badHappenstance ("Write failed");

SEEK AND READ OPERATION -- Far more complex than higher level methods


Code:
// Return to the beginning for input
   if (_lseek (ooFile, 0, SEEK_SET) == -1L)
      return badHappenstance ("Seek to beginning failed");

   // Read tokens until end of file or error
   nTokens = 0;
   while (1)
   {
      // Skip any whitespace
      while (status = _read (ooFile, sTrash, 1) == 1)
         if (!isspace (sTrash [0])) break;
      // Check for EOF or failure
      if (status < 0) return badHappenstance ("Failure to read data");
      else if (status == 0) break;
      sToken [0] = sTrash [0];
      for (nChars = 1; nChars < sizeof (sToken) - 1; nChars++)
      {
         status = _read (ooFile, &sToken [nChars], 1);
         // Check for EOF or failure
         if (status < 0) return badHappenstance ("Failure in reading data");
         else if ((status == 0) || (isspace (sToken [nChars])))
         {
            sToken [nChars] = '\0';
            break;
         }
      }
      // The token could be too long...
      if (nChars >= sizeof (sToken) - 1)
      {
         sTrash [0] = ' ';
         // Skip any remaining non-whitespace characters
         while (status = _read (ooFile, sTrash, 1) == 1)
            if (!isspace (sTrash [0])) break;
         // Check for EOF or failure
         if (status < 0) return badHappenstance ("Failure in reading data");
         else if (status == 0) break;
      }
      // Or we could have completed the token
      if (strlen (sToken) > 0) printf ("Token %d: %s\n", ++nTokens, sToken);
   }
   printf ("End of file\n");

   // Reposition to beginning
   if (_lseek (ooFile, 0, SEEK_SET) == -1L)
      return badHappenstance ("Seek to beginning failed");

   // Read one buffer's worth
   status = _read (ooFile, lineBuffer, sizeof (lineBuffer) - 1);
   if (status > 0)
      lineBuffer [status] = '\0';

   printf ("This is the line: %s", lineBuffer);
   _close (ooFile);

   return 0;
}


Example output:


Code:
Token 1: File
Token 2: data
End of file
This is the line: File data

 
webmaster forum
Activity
0%
 
New Poster
Posts: 1
Topics: 0
February 13, 2009, 02:06:52 AM

good questions
 
webmaster forum
polas  Offline
Activity
33.33%
 
Code Guru
Gender: Male
Posts: 1399
Topics: 85
WWW
February 13, 2009, 03:13:47 AM

good questions

Yup - hope it has helped you.... welcome to the forum by the way Smiley

Mesham Type Oriented Parallel Programming Language, Free online technical support
 
webmaster forum
Activity
0%
 
New Poster
Posts: 2
Topics: 0
WWW
April 20, 2010, 02:26:28 AM

Thank you guys for this good information .
 
webmaster forum
Activity
0%
 
New Poster
Posts: 2
Topics: 0
WWW
April 30, 2010, 05:58:44 AM

Thank you guys this is really helpful question -answers but it is very basic can any one provide some specific company interview question answers
 
webmaster forum
Admin  Offline
*
 
Code Guru
Location: India
Gender: Male
Posts: 1387
Topics: 105
NaviBuster NaviBuster
WWW
May 19, 2010, 09:41:32 AM

Thank you guys this is really helpful question -answers but it is very basic can any one provide some specific company interview question answers

This forum is for everyone and anyone can post a thread on it (as long it is not a spam), you can self start a new thread for interview questions and post some that you might already know. Your initiative will help everyone.
 
webmaster forum
Activity
0%
 
Regular Coder
Gender: Female
Posts: 85
Topics: 15
May 20, 2010, 06:38:03 PM

WOW

this is amazing

very great topic Admin, very helpful

Smiley

I'm trying to express myself Smiley

my blog: http://www.libertydash.blogspot.com/

smashwords: http://www.smashwords.com/books/view/91236
 
webmaster forum
Activity
0%
 
New Poster
Posts: 1
Topics: 0
August 20, 2010, 10:45:15 PM

Hi,

i m new in this forum ans i just need a help in it and i wish that this site will response me well.
« Last Edit: August 28, 2011, 08:02:30 AM by Admin »
 
webmaster forum
Activity
0%
 
Regular Coder
Gender: Female
Posts: 85
Topics: 15
September 11, 2010, 08:14:36 AM

hiiii

i m new in this forum ans i just need a help in it and i wish that this site will reponse me well,,

_____________________
"Want to get-on Google's first page and loads of traffic to your website? Hire a SEO Specialist from Ocean Groups   seo pecialist
"

you're in the right place to begin programming

I'm trying to express myself Smiley

my blog: http://www.libertydash.blogspot.com/

smashwords: http://www.smashwords.com/books/view/91236
 
webmaster forum
Corrinla  Offline
Activity
0%
 
New Coder
Posts: 28
Topics: 0
January 07, 2011, 07:18:13 PM

But before this standard was published, C++ was already widely used and therefore there is a lot of code out there written in pre-standard C++. Referring to ANSI-C++ explicitly differentiate it from pre-standard C++ code, which is incompatible in some ways.

pandora jewelry | wholesale
 
webmaster forum
lisaroy1  Offline
Activity
0%
 
New Poster
Gender: Female
Posts: 8
Topics: 1
WWW
February 09, 2011, 03:14:00 AM

Q. how does a main() in C++ is different from main() in C?
Ans-
in C++, you do not need to type "return 0;" statement in a [ int main() {} ]as it will be provided automatically but not in case of C.
 
webmaster forum
Life Is Good!
Activity
0%
 
Professional Coder
Gender: Female
Posts: 242
Topics: 3
WWW
May 20, 2011, 08:51:40 AM

woah, cool! you've compiled the answers to most of those 'bothering' objective questions..! good work guys..! thank you very much for the great pieces of information!

Affordable Custom Web Design Services
 
webmaster forum
kbelly  Offline
Activity
0%
 
New Poster
Posts: 3
Topics: 1
July 17, 2011, 11:42:37 PM

this is very useful information. It is very useful for new comers. I like it very much.
 
webmaster forum
kellylsn  Offline
Activity
0%
 
Professional Coder
Posts: 229
Topics: 7
July 19, 2011, 10:22:40 PM

Its very interested thread, the posting are all are very knowledgeable. It definitely improve our knowledge. Thanks a lot.

Payday Loan
Online Easy Loans
 
webmaster forum
dianna  Offline
Activity
0%
 
Regular Coder
Posts: 88
Topics: 10
WWW
July 30, 2011, 12:33:09 AM

What is inline function?
   An inline function is a programming language construct used to tell a compiler it should perform inline expansion on a particular function.  In other words, the compiler will insert the complete body of the function in every place in the code where that function is used.
 
.     What is templates?
   Templates are a feature of the c++ programming language that allow functions and classes to operate with generic types.  This allows a function or class to work on many different datatypes without being rewritten for each one.
 
   What is operator overloading?
   operator overloading (less commonly known as operato ad-hoc polymorphim) is a specific case of polymorphis in which some or all of operators like +, =, or == have different implementations depending on the types of their arguments
 
.     What is a reference?
   A reference is an alias (an alternate name) for an object.  It is frequently used for pass-by-reference.
 
.     What is the difference between method overloading and method overriding?
   Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters).  Method overriding is the ability of the inherited class rewriting the virtual method of the base class.
 
.     Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible ?
   Virtual Constructor doesn't exist.  Constructor can’t be virtual as the constructor is a code which is responsible for creating a instance of a class and it can’t be delegated to any other object by virtual keyword means.
 
.     What is a class
   The C++ programming language allows programmers to separate program-specifiy datatype through the use of classes.  Instances of these datatypes are known as objects and can contain member variables member functions and overloaded operators defined by the programmer.  Syntactically, classes are extensions of the C struct, which cannot contain functions or overloaded operators.

Pakistan's Local Search engine
 
webmaster forum
colakyngo  Offline
Activity
0%
 
New Poster
Posts: 1
Topics: 0
August 03, 2011, 01:57:58 AM

Hi,

Thanks very much for this comment.  It help me to think about my ideals.

Tks again and pls keep posting.
 
webmaster forum
kellylsn  Offline
Activity
0%
 
Professional Coder
Posts: 229
Topics: 7
August 09, 2011, 04:07:13 AM

Thanks for these valuable questions and answers.

Payday Loan
Online Easy Loans
 
webmaster forum
netshet  Offline
Activity
0%
 
Regular Coder
Posts: 73
Topics: 2
WWW
August 15, 2011, 12:33:18 AM

How do exceptions simplify my function return type and parameter types?
   When you use return codes, you often need two or more distinct return values: one to indicate that the function succeeded and to give the computed result, and another propagate the error information back to the caller.
 
    How can I handle a destructor that fails?
   Write a message to a log-file. Or call Aunt Tilda. But do not throw an exception.
 
    What's the difference between how virtual and non-virtual member functions are called?
   Non-virtual member functions are resolved statically. That is, the member function is selected statically (at compile-time) based on the type of the pointer (or reference) to the object.In contrast, virtual member functions are resolved dynamically (at run-time).

hair transplant
 
  Email this topic  |  Print
Pages: [1]   Go Up
 
Jump to:  



Powered by SMF 1.1.15 | SMF © 2011, Simple Machines


Google visited last this page February 06, 2012, 02:57:25 AM