Display a String in C++

0
CPP

In this program, the user will be asked to enter a string which will be stored in a string variable str. Finally, it will be displayed on the console.

#include <iostream>
using namespace std;

int main() 
{
    string str;
    
    cout << "Please enter the string: ";
    cin >> str;
    
    cout << str;
    return 0;
}

First, we will have to include the iostream library to the program which is resposible for taking input and displaying the output. Next a string variable str will be created. The user will be asked in line 11 to enter a string which will be stored in the variable str. Finally, the string variable str will be displayed on the console.

Output

Please enter the string: Hello
Hello

The only drawback of using cin to take input from a user as a string is that we cannot store strings with spaces. E.g., if we try to store “Hello World” in str and then try to display it on the console then it will only show us “Hello”. Anything written after the first space will be discarded.

One solution to overcome this drawback is to use getline. The getline will take the complete input from the console including after the spaces and then store it in the desired string variable.

#include <iostream>
using namespace std;

int main() 
{
    string str;
    
    cout << "Please enter the string: ";
    getline(cin, str);
    
    cout << str;
    return 0;
}

Output

Please enter the string: Hello World
Hello World

LEAVE A REPLY

Please enter your comment!
Please enter your name here