×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to read a string

Learn, how to read a string in C++ using cin and cin.getline()?
[Last updated : February 28, 2023]

Reading a string in C++

Here, we will learn how to read string with/without spaces using cin and cin.getline() in C++? Here, we are writing two programs, first program will read a string using cin (without spaces) and second proram will read a string with spaces using cin.getline().

Program to read a string using cin in C++

#include <iostream>
using namespace std;

int main()
{
    //declaring string (character array)
    char text[100] = { 0 };

    cout << "Enter a string: ";
    cin >> text;

    cout << "Input string is: " << text << endl;

    return 0;
}

Output

Enter a string: Hello friends how are you?
Input string is: Hello

Consider the output, input string was "Hello friends how are you? but, only "Hello" stored in variable text. Because cin does not take string after the string, as string found cin terminates reading and assign NULL.

Program to read a string using cin.getline() in C++

#include <iostream>
using namespace std;

int main()
{
    //declaring string (character array)
    char text[100] = { 0 };

    cout << "Enter a string: ";
    cin.getline(text, 100);

    cout << "Input string is: " << text << endl;

    return 0;
}

Output

Enter a string: Hello friends how are you?
Input string is: Hello friends how are you?

Here, complete string stored in text, cin.getline() allows to get spaces also. I would recommend to read this tutorial How to read a string with spaces in C++?

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.