C++ String Input

Introduction

Preferred way of accepting a string from the standard input is via the std::getline function which takes std::cin and our string as parameters:

#include <iostream> 
#include <string> 

int main() /*w w  w .  j a v a2 s  .com*/
{ 
    std::string s; 
    std::cout << "Please enter a string: "; 
    std::getline(std::cin, s); 
    std::cout << "You entered: " << s; 
} 

We use the std::getline because our string can contain white spaces.

If we used the std::cin function alone, it would accept only a part of the string.

The std::getline function has the following signature:

std::getline(read_from, into); 

The function reads a line of text from the standard input into a string variable.

To use the std::string type, include the <string> header explicitly.




PreviousNext

Related