Home  >  Article  >  Backend Development  >  Why can\'t I output strings using `cout`?

Why can\'t I output strings using `cout`?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 08:03:30564browse

Why can't I output strings using `cout`?

Troubleshooting the Inability to Output Strings with cout

Why is it that you cannot output strings using cout? Let's delve into this issue and provide a solution.

In your code snippet:

<code class="cpp">string text;
text = WordList[i].substr(0, 20);
cout << "String is  : " << text << endl;

You will encounter the following error:

Error 2   error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)  c:\users\mollasadra\documents\visual studio 2008\projects\barnamec\barnamec\barnamec.cpp    67  barnamec**

To resolve this error, you must include the necessary headers:

<code class="cpp">#include <string>
#include <iostream></code>

The header contains the declaration of the std::string class, while the header includes the definition for the std::cout object and the << operator.

Here is the corrected code:

<code class="cpp">#include <string>
#include <iostream>

string text;
text = WordList[i].substr(0, 20);
cout << "String is  : " << text << endl;</code>

Now, you should be able to successfully output strings using cout.

The above is the detailed content of Why can\'t I output strings using `cout`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn