You are here:

C++/storing a sentence in a string variable



im using dev c++ and i wanted to know how i can store a whole sentence to a string variable.


Sorry but your question is not very clear as to what exactly you are trying to achieve. I present some common possibilities here. If these do not cover what you are trying to do then please ask another (possibly followup) question giving greater clarification.

Note that I am presuming the version of DevC++ you are using is fairly up to date and has a reasonably standard C++ library implementation.

You can store a sentence to a string object like so for example:

   #include <string>

   int main()
       std::string sentence( "the quick brown fox jumped over the lazy dog." );  // Initialisation (construction)
       sentence = "Now we store another sentence.";          // Assignment

   // ...


But you could mean how can you input from the console a whole sentence and store it in a string object. If so then you can use the one of the std::getline functions that work with std::string objects:

   #include <string>
   #include <iostream>

   int main()
       std::cout << "Enter a sentence. Press the Enter key when you are done: ";

       std::string sentence;
       std::getline( std::cin, sentence );

   // ...


The std::getline functions takes a stream (a std::ostream object) to read character data from and a std::string object into which to store the results. It can also take an optional third parameter that is a character that specifies the delimiting character used to indicate the point at which to stop reading. The default, as used here, it is the newline ('\n') character. The delimiting character is read but _not_ stored in the string.

The std::getline function will read (and store) all characters until one of the following occur:
   - if the streams width is greater than 0 and width() characters are stored
   - strm.good() is false - i.e. there is a formatting or fatal stream error
   - the delimiter character is read (or '\n' is read if no delimiter character given - as here)
   - the maximum size of the string (i.e. sentence.max_size() ) characters are stored.
       A std::string::max_size() value is typically a large value.

Both the above assume that you mean the C++ standard library string type and not zero terminated arrays of char that are the C-style of strings. If using the C style of strings you can do the following:

   #include <cstring>

   int main()
       char sentence[] = "the quick brown fox jumped over the lazy dog" ;      // Initialisation
       size_t sentenceLength( strlen(sentence) );
       strncpy( sentence, "Now we store another sentence.", sentenceLength );  // "Assignment"

   // ...


   #include <iostream>

   int main()
       std::cout << "Enter a sentence. Press the Enter key when you are done: ";

       unsigned int const MaxSentenceCharacterLength(255);
       unsigned int const SentenceArraySize(MaxSentenceCharacterLength+1);
       char sentence[SentenceArraySize];
       std::cin.getline( sentence, SentenceArraySize );

   // ...


Note the care taken with C-strings to ensure we do not overwrite memory beyond the bounds of the underlying char arrays. This is needed as the character arrays used for C-strings are of a fixed sizes and these simple examples do not go into the complexities of dynamically allocating and reallocating such arrays to cope with varying (expanding) sizes of data.

Operations on C-strings require the use of the C (and thereby C++) library functions for manipulating C-strings declared in the <cstring> header. Here I use strlen to obtain the character length of the initial sentence so it can be passed as the limit of characters to copy to the strncpy function to ensure that if the 2nd sentence were longer than the 1st it does not cause writing past the end of the array - a real no no. Note that sentenceLength is the number of characters in the sentence array _less_ the terminating zero. This is exactly what is required to work with strncpy.

In the reading from console into a C-string example note that the getline member functions of ostream objects such as std::cin work similarly to the std::getline functions that work with std::string objects. The difference is that they take a (pointer to) a C-style string and, as with strncpy (and for the same reason), a value specifying the maximum number of characters to read. Thus rather than (possibly) reading up to the std::string::max_size() number of characters that condition is replaced with reading up to the passed maximum number of characters to read minus 1 (in this case SentenceArraySize-1, which is the same value as MaxSentenceCharacterLength).

Notice that the meaning of the limit parameter to getline and strncpy differ:

   std::ostream::getline writes up to limit-1 characters and _always_ terminates the written to C-string with a zero character.
   strncpy writes up to limit characters and will not terminate the C-string char array written to if there is no zero character in the first limit-characters in the copied data.

Hope this answers your question. If it does not or you have further queries then please ask another question, preferably with a greater degree of clarification and detail on what you are really trying to do and need help with.  


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


©2017 All rights reserved.