Print String in C++

We can print a string generally in three ways. They are

  • Print string in C++ Using std::cout operator
  • Using std::copy operator
  • Print string in C++ Using printf() function
Print String in C++

Print String in C++ Using std::cout Operator

Cout operator is a special function in C++ to display string, numbers, symbols, etc. If you want to display anything then you can get it from cout operator. << operator is essential to display the string by using cout operator.

#include <iostream>
#include <string>
#include <iterator>

using std::cout; using std::cin;
using std::endl; using std::string;

int main(){
    string s1 = "This string will be printed";
    cout << s1;
    cout << endl;

    return EXIT_SUCCESS;
}

Output

Here the input string is given manually in the program. The screen doesn’t ask anything from the user.

This string will be printed

Print String in C++ Using std::copy Operator

You can use the copy operator to copy the given string and stores in a variable. The value of the variable displays as output.

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::copy;

int main(){
    string s1 = "This string will be printed";

    copy(s1.begin(), s1.end(),
         std::ostream_iterator<char>(cout, ""));
    cout << endl;

    return EXIT_SUCCESS;
}
Read Also : Reverse a Number in C++

Print String in C++ Using Printf() Function

Printf() is the special function to display any string in C language. It is also used in C++ language sometimes by calling function.

#include <iostream>
#include <string>
#include <iterator>

using std::cout; using std::cin;
using std::endl; using std::string;

int main(){
    string s1 = "This string will be printed";
    cout << s1;
    cout << endl;

    printf("%s", s1.c_str());
    cout << endl;

    return EXIT_SUCCESS;
}

Final Words

I hope this article helps you to Print String in C++ Program. If you face any issues please let me know via the comment section. Share this article with other C++ program developers via social networks.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment