You are here:

C++/c++ strings


i want to enter string in mine program
1st method is :
char h[44];
cout<<"enter your name ";
you will get what you have entered.
is there any other method for doing the same

Yes. Quite a few in fact. However, if we restrict ourselves to using C++ standard library features, and exclude the C library features the C++ library also includes then this leaves us still with several ways to achieve the same thing.

First a few notes on your code:

1/ main() is incorrect C++, use int main() instead. For some broken compilers you may be forced to add a

   return 0;

statement as the final line of main.

2/ getch() is non-standard C and C++, and is therefore implementation specific (i.e. specific to the producer of the compiler and its runtime support library).

3/ What happens if I enter a string longer than 43 characters?
Using un-checked fixed length buffers such as the use of h in your program is a classic exploit by malicious personages in real life (buffer overrun).

4/ C++ standard library entities are all in the std namespace so cin and cout should more correctly be std::cin and std::cout, assuming you are using a fairly recent compiler.

OK so if we stick with C-style strings then we can use one of the get member functions to std::istream, the most common being getline, which has the useful feature that it can read a whole line of text and not stop at the first whitespace character:

   std::cin.getline( h, 44 );

Note that getline takes both the buffer for the characters and a count value. Up to count-1 characters will be read into the provided buffer and the string terminated with a '\0' as is required for C-style strings. Thus in this example up to 43 characters are read into h, and, assuming 43 characters are read then the 44th character (at position 43 - remember C and C++ arrays are indexed from 0) will be zero. Less character will be read if a newline character is encountered before then. The newline character is read but _not_ placed in the buffer.

There is a similar function get, which differs from getline in that the newline character is not read if encountered.

Both get and getline have a second from which has a third, character, parameter which specifies a delimiting character explicitly, so you can read up to delimiters other than newline, e.g.:

   std::cin.getline( h, 44, ',' );

The above will read up to 43 characters, or to the next comma, reading but not placing the comma in the string buffer h.

The get function also has variations that read single characters.

You will note that I have used 44 again - your code would now have this value twice, which leaves the possibility of changing one instance of 44 but not the other. Suppose you reduced the size of h to 22 characters - but forgot to reduce the count value passed to getline or get - ouch! Now it would be quite easy to read off the end of your buffer. Hence it is a good idea to name such so called magic numbers - this also gives readers of your code a hint of what the value means in the context of the code:

   int main()
       const unsigned int MaxStringSize(43);
       const unsigned int StringBufferSize(MaxStringSize+1);
       char h[StringBufferSize];

       cout<<"enter your name ";

       cin.getline(h, StringBufferSize);

   // ...

There are also the member functions read and readsome that read characters from a stream into a character buffer but they do _not_ terminate the string and so can be used to read raw binary (byte) data. I shall not go into details here. You can look them up in any decent C++ IOStreams reference.

The next way to read strings is not to use C strings at all but to use the standard C++ library class std::string. To use std::string include <string>:

   #include <string>

   int main()
       std::string name;

       std::cout<<"enter your name ";

       std::cin >> name;

   // ...

The std::string class has many operations that can be performed on string objects. However of particular interest here is the fact that it takes care of the memory management side of things for us, so that pesky maximum buffer size goes away. Of course std::string can still run out of memory if very, very long strings are encountered, but this is a lot less hassle than the previous situation. They can also be copied like other values - which C strings cannot (you have to allocate the destination array and then use strcpy). Again a good C++ library reference will go into details on std::string. One operation of interest is the std::string::size() or std::string::length() functions. They are synonymous, and return the length in characters of the string.

Now we cannot use the std::istream::getline function with std::string. However, the <string> header declares stand alone getline functions to work with streams and strings:

   #include <string>

   int main()
       const unsigned int MaxNameLength(43);

       std::string name;

       std::cout<<"enter your name ";

       std::getline(std::cin, name);

   // example of using std::string::size() :
       if ( name.size() > MaxNameLength ) ...

   // ...

Note: I use "The C++ Standard Library A Tutorial and Reference" by Nicolai M. Josuttis as my primary C++ standard library reference.

Hope this helps. If not please post a further question.  


All Answers

Answers by Expert:

Ask Experts


Ralph McArdell


I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.


My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at


©2016 All rights reserved.